2016-04-14 35 views
0

我有兩個表是這樣的:插入記錄到帶環的表從其它表數據

SupplyListIDSupply是主鍵)

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

SupplyIndexIDSupplyIndex是複合主鍵)

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

這些表格相互關聯,IDSupply

我想通過SQL中的查詢將錯過的記錄插入到SupplyIndex表中。換句話說,我的預期結果是SupplyIndex表像下面(Index必須從SupplyList表1至Qty包括數字)

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中直接。

你能幫我嗎?

感謝

回答

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 

我用數字表來完成這個

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

--final部分檢查和其他table..same查詢isnert如上所述帶插入並存在

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) 
+0

感謝您的回覆。它不適合我。請檢查我在SupplyIndex表中的編輯。我需要停泊幫助。謝謝 –

+0

你能提供更多的信息嗎?你需要替換你的表名和安裝號碼錶 – TheGameiswar

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 
+0

來自MSDN的Tom Cooper解決它。 –