Copy rows from the same table and update the ID column

前端 未结 8 448
情歌与酒
情歌与酒 2021-02-01 02:09

I have the following table

\"alt

I have inserted Product B to it and it gives me an ID of 15

8条回答
  •  醉话见心
    2021-02-01 02:48

    Can use MERGE on SQL Server 2008, has the advantage of using OUTPUT to return the DefID values, assuming they are auto-generated e.g.

    MERGE INTO ProductDefinition
    USING (
           SELECT 16, P1.Definition, P1.Description
             FROM ProductDefinition AS P1
            WHERE P1.ProdID = 15
          ) AS source (ProdID, Definition, Description)
    ON 0 = 1
    WHEN NOT MATCHED THEN
       INSERT (ProdID, Definition, Description)
       VALUES (ProdID, Definition, Description)
       OUTPUT inserted.DefID, inserted.ProdID, 
                 inserted.Definition, inserted.Description;
    

提交回复
热议问题