2

I need to insert data into a table and I need to output the newly inserted ids from the destination table mapped alongside the Ids from the source table. I have the following query:

DECLARE @mapping TABLE(
            DestId int,
            SourceId int);


INSERT INTO dest_table (column1, column2)
OUTPUT INSERTED.Id as DestId, src_table.Id as SourceId   INTO @mapping 
SELECT 
    src_table.column1,
    src_table.column2

FROM src_table

Which gives the following error:

The multi-part identifier "src_table.Id" could not be bound.

Normally, I would use a MERGE statement. However in this case it has to run on SQL Server 2005!!!

Is there any way of achieving this without resolving to a cursor and inserting values one by one?

1
  • You can't access the columns not part of the insert, unless you're using MERGE which i don't think is available in SQL Server 2005, you have to join them back by using some way of identify stuff, or use some hacks like re-purposing columns for IDs Commented Jul 30, 2023 at 18:17

2 Answers 2

0

It looks like a typo. The table is src_table1 (with the 1 at the end) whereas the aliasing is using src_table (without the 1 at the end). Can you just add the alias to the table?

DECLARE @mapping TABLE(
            DestId int,
            SourceId int);


INSERT INTO dest_table (column1, column2)
OUTPUT INSERTED.Id as DestId, src_table.Id as SourceId   INTO @mapping 
SELECT 
    src_table.column1,
    src_table.column2

FROM src_table1 src_table
Sign up to request clarification or add additional context in comments.

1 Comment

Ooops, thanks for pointing that out! The typo was only in my question though! The table is actually meant to be src_table. It is still an issue with the corrected table name. I have edited my question.
-1

I know this is an old question, but you can abuse a MERGE statement to allow the referencing of the source table in the OUTPUT clause

DECLARE @mapping TABLE (
    DestId int,
    SourceId int
);

MERGE INTO dest_table AS T 
USING src_table1 AS S ON 1=0 -- false predicate will ALWAYS not match!
WHEN NOT MATCHED THEN 
    INSERT (column1, column2) 
    VALUES (S.column1, S.column2) 
    OUTPUT inserted.id as DestID, S.id AS SourceID INTO @mapping
;

the trick is the 1=0 in the merge predicate forcing it to always use the INSERT WHEN NOT MATCHED clause of the MERGE.

Edited to add: In response to the downvote I have since realised the question explicitly discounts the use of MERGE due to SQL-2005 being in use, however I thought the trick outlined in the answer above to be interesting enough to record here. If the community feels further downvotes are warranted I will delete my answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.