MERGE to make Target match Source
suggest changeMERGE 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents