T-SQL: INSERT original value in OUTPUT clause

前端 未结 1 1382
闹比i
闹比i 2021-01-04 00:22

I have a table Items (ItemID, Name, ...) where ItemID is auto-generated identity

I want to add rows into this table FROM select on this same table.

相关标签:
1条回答
  • 2021-01-04 00:49

    If you are on SQL Server 2008+, you can use MERGE for getting both the current and the new ID. The technique is described in this question.

    For your example the statement might look like this:

    MERGE INTO
      Items AS t
    USING
      (
        SELECT *
        FROM Items
        WHERE Name = 'Cat'
      ) AS s
    ON
      0 = 1
    WHEN NOT MATCHED BY TARGET THEN
      INSERT (target_column_list) VALUES (source_column_list)
    OUTPUT
      S.ItemID, INSERTED.ItemID INTO @ID2ID (OldItemID, NewItemID)
    ;
    
    0 讨论(0)
提交回复
热议问题