Created
May 29, 2024 08:28
-
-
Save zkarj735/c76961a0a7cd45e52f620731d8bcbe20 to your computer and use it in GitHub Desktop.
A technique to "update or insert" a single row in a DB2 table.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- DB2 has a MERGE statement which is designed to merge the rows from one table into another. | |
-- This technique adapts that to the case of a single row of literal values (such as might be provided in an application program). | |
-- This is informally known as an 'upsert' - a portmanteau of "update" and "insert". | |
-- The key parts of this statement are: | |
-- 1. The USING clause provides the values for the entire row, and also provides column names for these. | |
-- 2. The ON clause is the means for detecting an existing record (like a join's ON clause). | |
-- 3. The WHEN MATCHED clause specifies which columns to update in an existing record. Obviously this won't contain the keys, but needn't contain all the other columns either. | |
-- 4. The INSERT VALUES clause uses the column names provided in the USING clause. | |
-- Technically, the INSERT needn't specify every column (e.g. allowing defaults to be used, or ID columns to generate) | |
MERGE INTO Products AS Target | |
USING (VALUES (101, 'New Product', 19.99) ) AS Source (ProductID, ProductName, ProductPrice) | |
ON Target.ProductID = Source.ProductID | |
WHEN MATCHED THEN | |
UPDATE SET Target.ProductName = Source.ProductName, | |
Target.ProductPrice = Source.ProductPrice | |
WHEN NOT MATCHED BY TARGET THEN | |
INSERT VALUES (Source.ProductID, Source.ProductName, Source.ProductPrice); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment