So, here is the conundrum I am trying to solve, let us say I have the following tables, scripted as create statements
create table table1 (pk int identity(1,1) primary key, a int, b int)
create table table2 (pk int identity(100,1) primary key, a int, b int)
create table tbllink (tbl1pk int, tbl2pk int)
now, due to some requirements oversight, I now find myself in a situation where I need to take some of the records from table1, insert them into table2 after performing some kind of ad hoc calculation, and I need to be able to link them back to each other via the bridge tbllink.
This is fairly easy to do with a cursor, see below for cursor pseudo
cursor for select pk, a, b from table1 where (some clause)
fetch cursor into @pk, @a, @b
while @@fetch_status
begin
insert into table2 (a, b)
output @pk, inserted.pk into tbllink
values (@a, @b + 5)
fetch cursor into @pk, @a, @b
end
This works and gets me exactly the results I need, but what I would really like to be able to do is something like this.
insert into table2 (a, b)
output table1.pk, inserted.pk into tbllink
select a, b + 5 from table1 where (some clause)
this doesn't compile, though. Is there any way to accomplish this, or should I just use the cursor? Thanks.