-1

在我的产品表中,我有 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 个州插入一行。我可以用另一双眼睛 - 我在这里做错了什么?

4

2 回答 2

5

你为什么将游标用于基于集合的操作?

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

insert into ProductToState(ProductID, [State])
    select ProductId, State
    from (select distinct [State] from lookUpAreaFactor) s cross join
         (select distinct ProductId from Product) p;
于 2014-07-15T12:25:57.727 回答
1

你需要使用游标吗?如果你不这样做,你可以通过简单的交叉连接来做到这一点

INSERT INTO ProductToState 
        ( [STATE], productid )
SELECT DISTINCT  s.[State], p.productid
FROM products p CROSS JOIN lookUpAreaFactor s
于 2014-07-15T12:29:44.133 回答