Insert Into… Merge… Select (SQL Server)

前端 未结 1 643
梦谈多话
梦谈多话 2020-11-27 23:15

I could use your expertise. I have the following code:

INSERT INTO Table3 (Column2, Column3, Column4, Column5)
SELECT null, 110, Table1.ID, Table2.Column2
FR         


        
相关标签:
1条回答
  • 2020-11-27 23:52

    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); 
    
    0 讨论(0)
提交回复
热议问题