I have two tables:
Sheet(Id, Name, CreatedById, CreatedOn)SheetColumn(Id, SheetId, ColumnName)
I want to copy some rows from my Sheet table with newIds using givenIds. Then I want to insert new and old ids to a temp table variable. Then using this temp table I want to copy related SheetColumn rows with new ids. But OUTPUT line throws an error:
The multi-part identifier "OldRows.Id" could not be bound
How can I achieve this with this or another approach?
For this I wrote something like this:
DECLARE @TempSheetMapping TABLE
(
OldSheetId INT,
NewSheetId INT
);
WITH OldRows AS
(
SELECT *
FROM Sheet
WHERE Id IN (.....)
)
INSERT INTO Sheet (Name, CreatedById, CreatedOn)
-- ERROR: The multi-part identifier "OldRows.Id" could not be bound.
OUTPUT inserted.Id AS NewSheetId, OldRows.Id AS OldSheetId
INTO @TempSheetMapping (NewSheetId, OldSheetId)
SELECT Name, CreatedById, CreatedOn
FROM OldRows;
INSERT INTO SheetColumn (SheetId, ColumnName)
SELECT t.NewSheetId, sc.ColumnName
FROM SheetColumn sc
JOIN @TempSheetMapping t ON sc.SheetId = t.OldSheetId;
OUTPUTclause can only reference theInsertedpseudo table - it cannot reference other tables involved