Is there a way to determine whether a record was matched or not (whether the record was inserted or updated) after calling MERGE?
Ideally I’d like to output it to a parameter.
Edit:
I’ve got the merge statement outputting what happened in my management studio using the following statement:
Say I had the following merge statement:
MERGE INTO TestTable as target
USING ( select '00D81CB4EA0842EF9E158BB8FEC48A1E' )
AS source (Guid)
ON ( target.Guid = source.Guid )
WHEN MATCHED THEN
UPDATE SET Test_Column = NULL
WHEN NOT MATCHED THEN
INSERT (Guid, Test_Column) VALUES ('00D81CB4EA0842EF9E158BB8FEC48A1E', NULL)
OUTPUT $action;
I’m trying to use a parameter to get the ‘$action’ output.
What you could do is create a temporary table (or a table variable) and send your output there – add some meaningful fields to your OUTPUT clause to make it clear what row was
affected by what action:
UPDATE: ah, okay, so you want to call this from .NET ! Well, in that case, just call it using the
.ExecuteReader()method on yourSqlCommandobject – the stuff you’re outputting usingOUTPUT...will be returned to the .NET caller as a result set – you can loop through that:You should get back the resulting “$action” from that data reader.