Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL MERGE - finding out which action it took

I need to know if a MERGE statement performed an INSERT. In my scenario, the insert is either 0 or 1 rows.

Test code:

DECLARE @t table (C1 int, C2 int)
DECLARE @C1 INT, @C2 INT

set @c1 = 1
set @c2 = 1

MERGE       @t as tgt
USING       (SELECT @C1, @C2) AS src (C1, C2)
ON          (tgt.C1 = src.C1)
    WHEN MATCHED AND tgt.C2 != src.C2 THEN
        UPDATE SET tgt.C2 = src.C2
    WHEN NOT MATCHED BY TARGET THEN
        INSERT VALUES (src.C1, src. C2)
    OUTPUT deleted.*, $action, inserted.*;

SELECT inserted.*

The last line doesn't compile (no scope, unlike a trigger). I can't get access to @action, or the output. Actually, I don't want any output meta data.

How can I do this?

like image 531
IamIC Avatar asked Dec 22 '10 08:12

IamIC


1 Answers

You can OUTPUT into a table variable and then retrieve from that. Try this:

DECLARE @t table (C1 int, C2 int)
DECLARE @C1 INT, @C2 INT
DECLARE @Output TABLE (DeletedC1 INT, DeletedC2 INT, ActionType VARCHAR(20), InsertedC1 INT, InsertedC2 INT)

set @c1 = 1
set @c2 = 1

MERGE       @t as tgt
USING       (SELECT @C1, @C2) AS src (C1, C2)
ON          (tgt.C1 = src.C1)
    WHEN MATCHED AND tgt.C2 != src.C2 THEN
        UPDATE SET tgt.C2 = src.C2
    WHEN NOT MATCHED BY TARGET THEN
        INSERT VALUES (src.C1, src. C2)
    OUTPUT deleted.*, $action, inserted.* INTO @Output;

SELECT * FROM @Output WHERE ActionType = 'INSERT'
like image 59
AdaTheDev Avatar answered Nov 02 '22 21:11

AdaTheDev