Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

Get Row Count of Insert/Update/Delete records in MERGE Statement MSDN TSQL fo ...

$
0
0
Get Row Count of Insert/Update/Delete records in MERGE Statement MSDN TSQLforum

> 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

Advertisements


Viewing all articles
Browse latest Browse all 3160

Latest Images

Trending Articles