2

我有两张表,一张称为 Product,另一张称为 ProductVariant。ProductVariant 具有来自 Product 的 ID。我需要在两个表上做简单的操作。

这是我提出的查询:

declare @id int

declare cur CURSOR LOCAL for
select @id = ProductID  from Product WHERE (Published = '0')

open cur

fetch next from cur into @id 

while @@FETCH_STATUS = 0 BEGIN

UPDATE Productvariant SET Cost = SalePrice WHERE VariantID = @id;
UPDATE ProductVariant SET SalePrice = 0.00 WHERE VariantID = @id; 

fetch next from cur into @id 
END

close cur
deallocate cur

但它给了我:Msg 154、Level 15、State 3、Line 4 变量赋值在游​​标声明中是不允许的。

谢谢

4

5 回答 5

3

你可以尝试类似的东西:

UPDATE ProductVariant SET Cost =SalePrice , SalePrice = 0.00
WHERE VariantID IN (SELECT productID FROM Product WHERE Published = '0')
于 2012-11-23T12:00:23.617 回答
1

如果您正在学习如何使用游标,只需从选择中删除 @id - 您已经使用 fetch next.... 行获取该值。

declare cur CURSOR LOCAL for
select ProductID  from Product WHERE (Published = '0')

但是应该使用比光标更好的另一种选择

declare @id int
declare @idTable as table(id int)

insert into @idTable
select ProductID  from Product WHERE (Published = '0')

while(exists(select top(1) id from @idTable)) 
begin
    select top(1) @id = id from @idTable

    UPDATE Productvariant SET Cost = SalePrice WHERE VariantID = @id;
    UPDATE ProductVariant SET SalePrice = 0.00 WHERE VariantID = @id; 

    delete top(1) from @idTable
end
于 2012-11-23T12:00:11.930 回答
1

前 4 行应该是:

declare @id int

declare cur CURSOR LOCAL for
select ProductID  from Product WHERE (Published = '0')
于 2012-11-23T11:57:38.160 回答
1

我会做这样的事情。

SQL小提琴

MS SQL Server 2008 架构设置

create table Product
(
  ProductID int,
  Published char(1)
);

create table ProductVariant
(
  VariantID int,
  Cost money,
  SalePrice money
);

insert into Product values
(1, '0'),
(2, '1'),
(3, '0')

insert into ProductVariant values
(1, 0, 10),
(1, 0, 11),
(2, 0, 20),
(2, 0, 21),
(3, 0, 30),
(3, 0, 31);

查询 1

UPDATE ProductVariant 
SET    Cost = SalePrice, 
       SalePrice = 0.00 
FROM   Product 
WHERE  Product.ProductID = ProductVariant.VariantID AND
       Product.Published = '0';

SELECT *
FROM ProductVariant;

结果

| VARIANTID | COST | SALEPRICE |
--------------------------------
|         1 |   10 |         0 |
|         1 |   11 |         0 |
|         2 |    0 |        20 |
|         2 |    0 |        21 |
|         3 |   30 |         0 |
|         3 |   31 |         0 |
于 2012-11-23T11:58:44.727 回答
0
declare cur CURSOR LOCAL for
select ProductID  from Product WHERE (Published = '0')

您不需要,select @id = ProductID因为这就是 fetch 为您所做的。它获取的值ProductID 并将其放入@id

希望有帮助

于 2012-11-23T12:03:11.547 回答