嵌套的SQL游标

时间:2014-07-15 12:21:47

标签: sql sql-server-2014 cursors

在我的产品表中,我有14种产品,对于每种产品,我需要在美国的每个州都有一排。我试图通过以下方式实现这一目标:

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个州插入一排。我可以用另一双眼睛 - 我在这里做错了什么?

2 个答案:

答案 0 :(得分:5)

为什么使用游标进行基于集合的操作?

我认为此查询可以满足您的需求:

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

答案 1 :(得分:1)

你需要使用游标吗?如果不这样做,您可以使用简单的交叉连接

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