I want to copy data between tables and build a mapping of old and new primary keys. I need the mapping to later update child tables.
What I want:
preamble
create table T1(Id int IDENTITY(1,1) primary key, X int, Y int, Z int)
create table T2(Id int IDENTITY(1,1) primary key, X int, Y int, Z int)
create table C1(Id int IDENTITY(1,1) primary key, T1_Id int not null foreign key references T1(Id), A int)
create table C2(Id int IDENTITY(1,1) primary key, T2_Id int not null foreign key references T2(Id), A int)
code
declare @keyMapping table(oldId int, [newId] int)
insert into T2 (X, Y, Z)
output INSERTED.ID, T1.ID into @keyMapping
select X, Y, Z from T1;
insert into C2 (T2_Id, A)
select km.newId, C1.A from C1
join @keyMapping km on C1.T1_Id = km.oldId
Unfortunately this fails with The multi-part identifier "T1.ID" could not be bound.
.
Is there a way to select something else besides the inserted values into the OUTPUT? Or is there another way to do what I want?