运行MSsql查询类似foreach的内容

时间:2012-11-23 11:52:02

标签: sql-server

我有两个表,一个叫做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 游标声明中不允许使用变量赋值。

由于

5 个答案:

答案 0 :(得分:2)

您可以尝试以下方式:

UPDATE ProductVariant SET Cost =SalePrice , SalePrice = 0.00
WHERE VariantID IN (SELECT productID FROM Product WHERE Published = '0')

答案 1 :(得分:1)

前4行应该是:

declare @id int

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

答案 2 :(得分:1)

我会这样做。

SQL Fiddle

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;

<强> Results

| VARIANTID | COST | SALEPRICE |
--------------------------------
|         1 |   10 |         0 |
|         1 |   11 |         0 |
|         2 |    0 |        20 |
|         2 |    0 |        21 |
|         3 |   30 |         0 |
|         3 |   31 |         0 |

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

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

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

希望有所帮助