Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

Insert Into... Merge... Select (SQL Server)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...