-1

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;
2
  • 1
    The OUTPUT clause can only reference the Inserted pseudo table - it cannot reference other tables involved Commented Sep 28, 2024 at 14:13
  • @marc_s How can I solve this problem? Commented Sep 28, 2024 at 14:14

1 Answer 1

0

I've solved it by using MERGE. Here is the final code:

DECLARE @TempSheetMapping TABLE (
    OldSheetId INT,
    NewSheetId INT
);

WITH OldRows AS (
    SELECT * FROM Sheet
    WHERE Id IN (.....)
)
MERGE INTO Sheet AS Target
USING OldRows AS Source
ON 1 = 0
WHEN NOT MATCHED THEN
    INSERT (Name, CreatedById, CreatedOn)
    VALUES (Name, CreatedById, CreatedOn)
OUTPUT inserted.Id as NewSheetId, OldRows.Id AS OldSheetId
INTO @TempSheetMapping (NewSheetId, OldSheetId);

INSERT INTO SheetColumn (SheetId, ColumnName)
SELECT t.NewSheetId, sc.ColumnName
FROM SheetColumn sc
JOIN @TempSheetMapping t ON sc.SheetId = t.OldSheetId;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.