Archive
Archive for March 29, 2017
Get Row Count of Insert/Update/Delete records in MERGE Statement – MSDN TSQL forum
March 29, 2017
Leave a comment
–> Question:
How can I get the numbers of records affected in the Merge statement, INSERT,UPDATE,DELETE separately and store it in a variable so I can get it in the application side?
Thanks !
–> My Answer:
You need to use OUTPUT clause with MERGE statement, try this:
DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20)); MERGE tblTarget AS Target USING (SELECT Col1,Col2 FROM tblSource) AS Source ON (Target.Col1 = Source.Col1) WHEN MATCHED THEN UPDATE SET target.Col2 = source.Col2 -- Need to get affected rows here WHEN NOT MATCHED BY TARGET THEN INSERT (Col1,Col2) VALUES (Col1,Col2); -- Need to get affected rows here OUTPUT $action INTO @SummaryOfChanges; --< check here -- Get the count of Insert/Update/Delete'd records from the below table variable SELECT Change, COUNT(*) AS CountPerChange FROM @SummaryOfChanges GROUP BY Change;
For more info on MERGE and OUTPUT clause statement check this link: http://technet.microsoft.com/en-us/library/bb510625.aspx
Categories: SQL Tips
MERGE, OUTPUT with MERGE