The set-based way to do the update correlated with the liner in SQL Server 2008, and then to use Merge ... CONCLUSION statement.
-- This table variable will hold the correlation between the two tables declare @NewLinks table (dst_id int, src_id int) merge TableB dst using TableA src on 1 = 0 --inserts all from src into dst, add WHERE-like limit here when not matched --should never match, since this is an INSERT-like query insert (<dst_column_list>) values (<src_column_list>) output INSERTED.<dst_surrogate_key>, src.<src_surrogate_key> into @NewLinks update src set src.ForeignKey = nl.dst_id from TableA src join @NewLinks nl on nl.src_id = src.Id
Since the INSERT statement (even in the form of INSERT ... SELECT) does not have a FROM clause, from_table_name cannot refer in its OUTPUT clause to fix the full correlation. Because MERGE always considers its USING clause to be a FROM clause, it can be used to simulate the INSERT ... SELECT construct, providing access to the source and destination tables in OUTPUT.
Using MERGE ... CONCLUSION to create UPDATE correlated with INSERT replaces inefficient use of RBAR solutions using cursors or loops with the contents of one temporary table or table-valued variable.
source share