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?
OldItemIDon the target table which you can fill with your "old" ItemID value. Also: if that ItemID is auto-generated, you should explicitly specify the list of columns (everything exceptItemID) both in yourINSERT INTO Items......as well as the correspondingSELECT (list of columns) FROM Items...statements. Otherwise, you'll be selecting "old" auto-generated ItemID values and trying to insert those into the auto-generated column again - which most likely won't even work