MERGE to make Target match Source

suggest change
MERGE INTO targetTable t
    USING sourceTable s
        ON t.PKID = s.PKID
    WHEN MATCHED AND NOT EXISTS (
            SELECT s.ColumnA, s.ColumnB, s.ColumnC
            INTERSECT
            SELECT t.ColumnA, t.ColumnB, t.ColumnC
            )
        THEN UPDATE SET
            t.ColumnA = s.ColumnA
            ,t.ColumnB = s.ColumnB
            ,t.ColumnC = s.ColumnC
    WHEN NOT MATCHED BY TARGET
        THEN INSERT (PKID, ColumnA, ColumnB, ColumnC)
        VALUES (s.PKID, s.ColumnA, s.ColumnB, s.ColumnC)
    WHEN NOT MATCHED BY SOURCE
        THEN DELETE
    ;

WHEN NOT MATCHED BY TARGET and BY SOURCE are SQL Server syntax. The AND NOT EXISTS test skips rows that have not changed. INTERSECT treats two NULLs as matching, so nullable columns do not need extra IS NULL tests. The second SELECT must use t.ColumnC, not s.ColumnC, or a change to ColumnC is invisible.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents