When writing an SQL Merge Statement, I wanted to avoid updating rows that hadn't changed.
The trick is to use EXISTS and EXCEPT
The page at http://www.made2mentor.com/2013/05/writing-t-sql-merge-statements-the-right-way/ explains this well
There's also a reference to Paul White's page https://www.sql.kiwi/
MERGE #Customer_New AS Target
USING #Customer_Orig AS Source
ON Target.CustomerNum = Source.CustomerNum
WHEN MATCHED AND EXISTS
(SELECT Source.CustomerName, Source.Planet
EXCEPT
SELECT Target.CustomerName, Target.Planet)
THEN
UPDATE SET
Target.CustomerName = Source.CustomerName
,Target.Planet = Source.Planet
WHEN NOT MATCHED BY TARGET
THEN
INSERT (CustomerNum, CustomerName, Planet)
VALUES (CustomerNum, Source.CustomerName, Source.Planet)
WHEN NOT MATCHED BY SOURCE THEN DELETE;
Comments
Post a Comment