Reputation: 93
I could use your expertise. I have the following code:
INSERT INTO Table3 (Column2, Column3, Column4, Column5)
SELECT null, 110, Table1.ID, Table2.Column2
FROM Table1
JOIN Table1Table2Link on Table1.ID=Table1Table2Link.Column1
JOIN Table2 on Table1Table2Link.Column2=Table2.ID
Now I need to take the Inserted.ID (Table3's Identity that is generated on insert) and Table2.ID and insert them into either a temporary table or a table variable. Normally I would use the OUTPUT clause, but OUTPUT cannot get data from across different tables. Now I believe it can be done with MERGE but I am not sure how to go about it. I need something like:
INSERT INTO Table3 (Column2, Column3, Column4, Column5)
OUTPUT Inserted.ID, Table2.ID into @MyTableVar
SELECT null, 110, Table1.ID, Table2.Column2
FROM Table1
JOIN Table1Table2Link on Table1.ID=Table1Table2Link.Column1
JOIN Table2 on Table1Table2Link.Column2=Table2.ID
I apologize if this is a duplicate question but I could not find anything.
Upvotes: 4
Views: 9291
Reputation: 82474
The trick is to populate the table with the MERGE
statement instead of an INSERT...SELECT
. That allowes you to use values from both inserted and source data in the output clause:
MERGE INTO Table3 USING
(
SELECT null as col2,
110 as col3,
Table1.ID as col4,
Table2.Column2 as col5,
Table2.Id as col6
FROM Table1
JOIN Table1Table2Link on Table1.ID=Table1Table2Link.Column1
JOIN Table2 on Table1Table2Link.Column2=Table2.ID
) AS s ON 1 = 0 -- Always not matched
WHEN NOT MATCHED THEN
INSERT (Column2, Column3, Column4, Column5)
VALUES (s.col2, s.col3, s.col4, s.col5)
OUTPUT Inserted.ID, s.col6
INTO @MyTableVar (insertedId, Table2Id);
Upvotes: 9