2014-07-15 124 views
-1

在我的产品表中,我有14个产品,并且对于每个产品,我需要在美国的每个州都有一行。我想通过以下来实现:嵌套SQL游标

begin tran 
declare @state varchar(2), 
     @productId int 

declare stateCursor CURSOR FOR 
select distinct [State] 
from lookUpAreaFactor 

declare productCursor CURSOR FOR 
select distinct productid 
from Product 


open stateCursor 
open productCursor 
FETCH NEXT from stateCursor into @state 
fetch next from productCursor into @productId 
while @@FETCH_STATUS = 0 
BEGIN 

     while @@FETCH_STATUS = 0 
     BEGIN 
      insert into ProductToState (ProductID,[State]) values (@productId,@state) 
      fetch next from productCursor into @productId 
     END 
    fetch next from stateCursor into @state 
END 

close stateCursor 
close productCursor 
select * from producttostate 
rollback 

它的第一个产品后,轰炸了 - 但它甚至没有插入行的所有50个州。我可以用另一双眼睛 - 我在这里做错了什么?

+0

你使用哪个DBMS? –

+0

我正在使用MSSMS – reds184

+0

MSSQL?哪个版本? –

回答

5

为什么你使用光标作为基于集合的操作?

我觉得这个查询你想要做什么:

insert into ProductToState(ProductID, [State]) 
    select ProductId, State 
    from (select distinct [State] from lookUpAreaFactor) s cross join 
     (select distinct ProductId from Product) p; 
+0

我不确定我可以用其他方式做到这一点。谢谢! – reds184

1

你需要使用游标?如果你不这样做,你可以用简单的交叉加入

INSERT INTO ProductToState 
     ([STATE], productid) 
SELECT DISTINCT s.[State], p.productid 
FROM products p CROSS JOIN lookUpAreaFactor s