Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: INSERT original value in OUTPUT clause

Tags:

tsql

insert

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. AND save into table variable the references between OriginalItemID and NewlyGeneratedID.

So I want it to look like the following:

DECLARE @ID2ID TABLE (OldItemID INT, NewItemID INT);

INSERT INTO Items OUTPUT Items.ItemID, INSERTED.ItemID INTO @ID2ID
SELECT * FROM Items WHERE Name = 'Cat';

BUT Items.ItemID obviously does not work here. Is there a workaround to make OUTPUT take original ItemID from the SELECT statement?

like image 304
Evgenyt Avatar asked May 20 '11 16:05

Evgenyt


1 Answers

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)
;
like image 159
Andriy M Avatar answered Sep 28 '22 03:09

Andriy M