我正在尝试查询2个表来为第三个表生成记录,这些表有时只链接到其他两个表,并将为第三个表生成的ID插入到第四个表中,我可以使用它来防止重新生成生成如果已在第三个表中生成记录。下面是我正在尝试做的简化示例。
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
我不能这样做,因为#T1.id1没有插入#T3。在不改变#T1到#T3的模式的情况下,我该怎么做才能将我想要的信息输入#T3Info?
我想最终:
id3 | id2 | value
---------+--------+---------
300 | NULL | a
301 | 201 | b
302 | 200 | c
id1 | id3
--------+--------
100 | 300
101 | 301
102 | 302
答案 0 :(得分:0)
我认为这句话可以解决问题!
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;
关于此可靠性的任何评论?