Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DB2, MERGE INTO update if value different

Tags:

sql

db2

I have this kind of DB2 request which work

MERGE INTO table_to_upsert AS tab
USING (VALUES
        (1, 2, 3),
        (4, 5, 6),
        (7, 8, 9)
        -- more rows
    ) AS merge (C1, C2, C3)
    ON tab.key_to_match = merge.key_to_match -- usually the primary key example : tab.C2 = merge.C2
    WHEN MATCHED THEN
        UPDATE SET tab.C1 = merge.C1,
                   tab.C2 = merge.C2,
                   tab.C3 = merge.C3
    WHEN NOT MATCHED THEN
        INSERT (C1, C2, C3)
        VALUES (merge.C1, merge.C2, merge.C3)

But now, what I want is, IF primary key already existe, then update, BUT only update C1 if the new value of C1 is different from the old one.

In theory something like that

MERGE INTO table_to_upsert AS tab
USING (VALUES
        (1, 2, 3),
        (4, 5, 6),
        (7, 8, 9)
        -- more rows
    ) AS merge (C1, C2, C3)
    ON tab.key_to_match = merge.key_to_match
    WHEN MATCHED THEN
        UPDATE SET tab.C1 = merge.C1,
                   tab.C2 = merge.C2,
                   tab.C3 = merge.C3
        WHERE tab.C1 != merge.C1
    WHEN NOT MATCHED THEN
        INSERT (C1, C2, C3)
        VALUES (merge.C1, merge.C2, merge.C3)

I add the WHERE tab.C1 != merge.C1 but it's not working, result in

Error: ILLEGAL SYMBOL WHERE; VALID SYMBOLS

like image 203
amdev Avatar asked Aug 11 '16 08:08

amdev


People also ask

Is MERGE into faster than UPDATE?

The UPDATE statement will most likely be more efficient than a MERGE if the all you are doing is updating rows. Given the complex nature of the MERGE command's match condition, it can result in more overhead to process the source and target rows.

Can we use select in MERGE statement?

MERGE Table1 AS tgt USING ( SELECT TOP 1 * FROM Table2 WHERE id = @id ) AS src ON ( tgt.id = src.id ) WHEN MATCHED THEN UPDATE SET qty = qty + @qty WHEN NOT MATCHED THEN INSERT itmid SELECT itmid FROM Table3 WHERE id = @id; sql.

Can we UPDATE view in Db2?

A view column that is derived from the same column as another column of the view can be updated, but both columns cannot be updated in the same UPDATE statement.


1 Answers

If I remember correctly, you can add one search condition to the matched line, i.e.

MERGE INTO table_to_upsert AS tab
USING (VALUES
        (1, 2, 3),
        (4, 5, 6),
        (7, 8, 9)
        -- more rows
    ) AS merge (C1, C2, C3)
    ON tab.key_to_match = merge.key_to_match
    WHEN MATCHED AND tab.C1 != merge.C1 THEN
        UPDATE SET tab.C1 = merge.C1,
                   tab.C2 = merge.C2,
                   tab.C3 = merge.C3
    WHEN NOT MATCHED THEN
        INSERT (C1, C2, C3)
        VALUES (merge.C1, merge.C2, merge.C3)
like image 178
RelativePHPNewbie Avatar answered Sep 19 '22 23:09

RelativePHPNewbie