Using the Merge Statement’s OUTPUT Clause to Match Inserted IDENTITY Fields with Source Table Fields
With this project I needed to insert data into table1 from table2 while simultaneously retrieving the identity field of table1, then insert that identity into table3 which mapped to table2 on a key that table1 did not have.
The OUTPUT clause when used with the input statment would not facilitate this because it could not return the identity and the source key in the same row. The result was to use the SQL Server 2008 Merge statement with the output clause.
Traditionally I would have looped the insert one record at a time and returned back both the values into variables, then inserted the identity into table3 by joining the keys on table2 and table 3.
INSERT INTO #MatchIDs
MERGE dbo.Table_1 t1
USING dbo.Table_2 t2
ON 1 = 0
WHEN NOT MATCHED
) AS mrg
WHERE mrg.output_action = 'INSERT'
The result is a statement that actually fools the MERGE by intentionally not matching any rows and just inserting all the records into the table.