开发者

SQL Server Merge statement

I am doing merge statement in my stored procedure. I need to count the rows during updates and inserts. If i use a common variable to get the updated rows (for both update and insert) how i can differ, this is the count which i got from update and this is the count which i go开发者_开发知识库t from insert. Please give me a better way


You can create a table variable to hold the action type then OUTPUT the pseudo $action column to it.

Example

/*Table to use as Merge Target*/
DECLARE @A TABLE (
 [id] [int] NOT NULL PRIMARY KEY CLUSTERED,
 [C] [varchar](200) NOT NULL)

/*Insert some initial data to be updated*/
 INSERT INTO @A
 SELECT 1, 'A' UNION ALL  SELECT 2, 'B'

/*Table to hold actions*/
 DECLARE @Actions TABLE(act CHAR(6))

/*Do the Merge*/ 
   MERGE @A AS target
    USING (VALUES (1, '@a'),( 2, '@b'),(3, 'C'),(4, 'D'),(5, 'E')) AS source (id, C)
    ON (target.id = source.id)
       WHEN MATCHED THEN 
        UPDATE SET C = source.C 
    WHEN NOT MATCHED THEN    
        INSERT (id, C)
        VALUES (source.id, source.C)
    OUTPUT $action INTO @Actions;

   /*Check the result*/ 
    SELECT act, COUNT(*) AS Cnt
    FROM @Actions
    GROUP BY act

Returns

act    Cnt
------ -----------
INSERT 3
UPDATE 2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜