I have a T-SQL
script that implements some synchronization logic using OUTPUT
clause in MERGE
s and INSERT
s.
Now I
Martin Smith is right, it is not possible to have two OUTPUT INTO
clauses in one MERGE
statement, but he is also right that it is possible to have one OUTPUT INTO
and one OUTPUT
clause. OUTPUT INTO
inserts its result set directly into the given table and the simple OUTPUT
returns result set to the caller.
So, you can wrap the MERGE
statement into a stored procedure and then use INSERT ... EXEC
to insert result set of the simple OUTPUT
into a second table.
CREATE PROCEDURE [dbo].[TestMerge]
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
MERGE TABLE_TARGET AS T
USING TABLE_SOURCE AS S
ON (T.Code = S.Code)
WHEN MATCHED AND T.IsDeleted = 0x0
THEN UPDATE SET ....
WHEN NOT MATCHED BY TARGET
THEN INSERT ....
OUTPUT inserted.SqlId, inserted.IncId
INTO sync_table
OUTPUT $action AS MergeAction, inserted.Name, inserted.Code;
END
Usage
INSERT INTO report_table
EXEC [dbo].[TestMerge];
This will insert rows into sync_table
and into report_table
.
If you examine execution plan you'll see that INSERT ... EXEC
creates a temporary table behind the scenes (see also The Hidden Costs of INSERT EXEC by
Adam Machanic).