You can use MERGE
together with OUTPUT
clause. OUTPUT
clause in MERGE
allows to access columns from both source and destination tables.
Query
MERGE
can insert, update and delete, but we need only simple insert, so the join criteria is always false (1=0
).
MERGE INTO TableA AS Dest
USING
(
SELECT name, CreatedDate, ExpiryDate
FROM #SomeSourceData
) AS Src
ON (1 = 0)
WHEN NOT MATCHED BY TARGET THEN
INSERT
(name)
VALUES
(Src.name)
OUTPUT inserted.IdA, Src.CreatedDate, Src.ExpiryDate
INTO TableB(IdA, CreatedDate, ExpiryDate)
;
Here I assume that TableA.IdA
is IDENTITY, so this column is not explicitly listed in the INSERT
statement. Same for column TableB.IdB
.
For each row in #SomeSourceData
there will be one row inserted into TableA
and one corresponding row inserted into TableB
.