如何知道MERGE操作是INSERT还是UPDATE?

时间:2013-09-24 14:55:30

标签: sql tsql sql-server-2008-r2

我想说,

MERGE INTO SHARE_AD_GROUP A
USING (
    SELECT SHARE_AD_GROUP_ID,
        SHARE_ID,
        AD_GROUP,
        SHARE_PERMISSIONS
    FROM SHARE_AD_GROUP
    WHERE SHARE_ID = @shareID AND AD_GROUP = @ownerId
) B ON (A.SHARE_AD_GROUP_ID = B.SHARE_AD_GROUP_ID)
WHEN MATCHED THEN
    UPDATE SET A.SHARE_PERMISSIONS = B.SHARE_PERMISSIONS
WHEN NOT MATCHED THEN
    INSERT (SHARE_PERMISSIONS) VALUES(@sharePermissions);

-- In Here how do I know that it is insert or update

如何知道INSERT或UPDATE后MERGE操作是INSERT还是UPDATE?

1 个答案:

答案 0 :(得分:1)

请参阅here

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;

SELECT Change, COUNT(*) AS CountPerChange
FROM @SummaryOfChanges
GROUP BY Change;