将记录插入到具有来自其他表数据的循环的表中

时间:2016-04-14 10:21:30

标签: sql-server-2008

我有两张这样的表:

SupplyList IDSupply是主键)

IDSupply  PartName  Qty
--------- --------- ----
1         C         10
2         B         4

SupplyIndex IDSupplyIndex是复合主键)

IDSupply  PartName  Index
--------- --------- ------
1           C        2
1           C        3
1           C        7
1           C        9
1           C        10

这些表格相互关联IDSupply

我想通过SQL中的查询将错过的记录插入SupplyIndex表。换句话说,我的预期结果为SupplyIndex表,如下所示(Index必须包含Qty表中从1到SupplyList的数字

IDSupply  PartName  Index
--------- --------- ------ (result)
1           C        1
1           C        2
1           C        3
1           C        4
1           C        5
1           C        6
1           C        7
1           C        8
1           C        9
1           C        10
2           B        1
2           B        2
2           B        3
2           B        4

之前我在VB.Net应用程序中完成了这项工作,现在我想直接在SQL Server中完成这项工作。

你能帮帮我吗?

由于

2 个答案:

答案 0 :(得分:1)

测试数据:

create table #supplylist
(
idsupply int,
partname char(20),
qty int
)

insert into #supplylist
select 1,'a',10
union all 
select 2,'c',4

create table #idsupply
(
 idsupply int,
 partname  char(20),
 indexx int
 )

 insert into #idsupply
 select 1,'a',10
 union all
 select 2,'c',3

我用Numbers表来完成这个

with cte
as
(
select 
idsupply,
partname,n
from 
#supplylist t
cross apply
(
select n from numbers where n <=qty
)b

- 最后一部分用于检查和isnert在其他table..same查询中,如上所示,带有insert和exists

with cte
as
(
select 
idsupply,
partname,n
from 
#supplylist t
cross apply
(
select n from numbers where n <=qty
)b
)
insert into #idsupply
select * from cte  t1 where not exists (select 1 from #idsupply t2 where t2.indexx=t1.n)

答案 1 :(得分:0)

Create Table #SupplyList(IDSupply int Primary Key,  PartName char(10),Qty int);
Insert #SupplyList(IDSupply, PartName, Qty) Values
(1,         'C',         10),
(2,         'B',         4);
Create Table #SupplyIndex(IDSupply int,  PartName char(10), [Index] int Primary Key (IdSupply, [Index]));
Insert #SupplyIndex(IDSupply, PartName, [Index]) Values
(1,           'C',        2),
(1,           'C',        3),
(1,           'C',        7),
(1,           'C',        9),
(1,           'C',        10);
;With cteMax As
(Select Max([Index]) As MaxIndex From #SupplyIndex),
cteNumbers As
(Select 1 As Number
Union All
Select Number + 1
From cteNumbers n
Cross Join cteMax m
Where n.Number < m.MaxIndex)
Merge #SupplyIndex t
Using (Select sl.IDSupply, sl.PartName, n.Number As Qty From #SupplyList sl Inner Join cteNumbers n On n.Number <= sl.Qty) s
On s.IDSupply = t.IDSupply And s.PartName = t.PartName And s.Qty = t.[Index]
When Not Matched Then Insert(IDSupply, PartName, [Index])  Values(s.IDSupply, s.PartName, s.Qty);

Select * From #SupplyIndex;


go
Drop Table #SupplyList;
go
Drop Table #SupplyIndex