我正在尝试一次从结果集中提取一条记录,以用作在表中插入数据的Select语句中的值。
select [Id]
from TBL
where PId = '123'
order by value
结果集1
222
333
444
555
查询2:
select [Id]
from TBL
where PId = '456'
order by value
结果集2
666
777
888
999
最后,我尝试通过从Result-set1
和Result-set2
中获取值来将数据插入表中。
insert into TBL ([Val], [Disp], [Seq], [Active], [DId], [PId])
select [Val], [Disp], [Seq], [Active], 'One Record From Result-set1', '1111'
from TBL
where PId = '2222'
and DId = 'One Record From Result-set2'
我读到游标有助于一次从结果集中提取一条记录,但是我不确定如何在我的场景中实现它。
insert into TBL ([Val], [Disp], [Seq], [Active], [DId], [PId])
select [Val], [Disp], [Seq], [Active], '222', '1111'
from TBL
where PId = '2222'
and DId = '666'
我试图摆脱硬编码222和666。
答案 0 :(得分:1)
假设两个查询都返回相同数量的记录(这是一个很大的假设),则可以使用使用行号创建的ID将两个数据集连接起来。 然后,您可以使用笛卡尔积将表中的记录插入到查询返回的结果中。
insert into TBL ([Val], [Disp], [Seq], [Active], [DId], [PId])
select [Val], [Disp], [Seq], [Active], cj.Id1, '1111'
from TBL
cross join (
select rs1.[Id] Id1, rs2.[Id] Id2
from (
select
row_number() over (partition by (select null) order by value) rn,
[Id]
from TBL where PId = '123'
) rs1
join (
select
row_number() over (partition by (select null) order by value) rn,
[Id]
from TBL where PId = '456'
) rs2
on rs1.rn=rs2.rn
) cj
where PId = '2222'
and DId = cj.Id2