开发者

Insert generated ID of link record with optional link into another table

I'm trying to query 2 tables to generate records for a third table which only sometimes links to both of the other tables, and insert the ID generated for the third table into a fourth table that I can use to prevent re-generation if already generated records in the third table. Below is a simplified example of what I'm trying to do.

create table #T1(id1 int primary key identity(100,1) not null, value nvarchar(10))
create table #T2(id2 int primary key identity(200,1) not null, value nvarchar(10))
insert into #T1(value) values('a')
insert into #T1(value) values('b')
insert into #T1(value) values('c')
insert into #T2(value) values('c')
insert into #T2(value) values('b')
insert into #T2(value) values('d')
create table #T3(id3 int primary key identity(300,1) not null, id2 int null, value nvarchar(10))
create table #T3Info(id1 int not null, id3 int not null)

insert into #T3(id2, value)
output inserted.id2
,#T1.id1
into #T3Info(id1, id3)
select #T2.id2, #T1.value
from #T1
left join #T2 on #T1.value = #T2.value
left join #T3Info join #T3 on #T3.id3 = #T3Info.id3
 on #T3Info.id1 = #T1.id1
where #T3Info.id1 is null

I can't do this because #T1.id1 is not being inserted into #T3. Without altering the schema of #T1 through #T3, what can I do to get the information I want into #T3Info?

I would like to end up with:

T3:

    id3  |  id2   |  value
---------+--------+---------
    300  |  NULL  |  a
    301  |   201  |  b
    302  |   200  |  c

T3Info:

   id1  |  id3
--开发者_运维知识库------+--------
   100  |  300
   101  |  301
   102  |  302


I think this statement will do the trick!

merge into #T3
using(
select #T1.id1, #T1.value
,#T2.id2
,#T3Info.id3
from #T1
left join #T2 on #T1.value = #T2.value
left join #T3Info on #T3Info.id1 = #T1.id1) src
on src.id3 = #T3.id3
when not matched by target then
insert(id2, value) values(src.id2, src.value)
output src.id1, inserted.id3
into #T3Info;

Any comments about the reliability of this?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜