Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 got from insert. Please give me a better way

like image 984
Robin clave Avatar asked Feb 28 '11 14:02

Robin clave


1 Answers

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
like image 196
Martin Smith Avatar answered Oct 14 '22 02:10

Martin Smith