嵌套的SQL游标

ff0*_*0e2 -1 sql cursors sql-server-2014

在我的产品表中,我有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
Run Code Online (Sandbox Code Playgroud)

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

Gor*_*off 5

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

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

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