DECLARE @UnitPrice DECIMAL(5, 2);
DECLARE @ProductId INT;
DECLARE UnitPriceUpdateCursor CURSOR
FOR
SELECT ProductID
FROM Products;
OPEN UnitPriceUpdateCursor;
FETCH NEXT FROM UnitPriceUpdateCursor INTO @ProductId;
WHILE(@@Fetch_Status = 0)
BEGIN
SELECT @UnitPrice = UnitPrice
FROM Products;
IF(@UnitPrice BETWEEN 5 AND 10)
BEGIN
UPDATE Products
SET
UnitPrice = 15.00
WHERE ProductID = @ProductId;
END;
ELSE
IF(@UnitPrice BETWEEN 15 AND 20)
BEGIN
UPDATE Products
SET
UnitPrice = 25
WHERE ProductID = @ProductId;
END;
FETCH NEXT FROM UnitPriceUpdateCursor INTO @ProductId;
END;
CLOSE UnitPriceUpdateCursor;
DEALLOCATE UnitPriceUpdateCursor;
SET NOCOUNT OFF;
答案 0 :(得分:3)
您可以使用单个更新语句替换整个游标逻辑。这应该做同样的事情。
Update Products
set UnitPrice = case when UnitPrice = 18.00 then 20
when UnitPrice < 25.00 then 30
else UnitPrice
end
- EDIT-- 在我发布原始答案后,问题发生了变化。这应该适应你想要的新逻辑。
Update Products
set UnitPrice = case when UnitPrice > 5 and UnitPrice < 10 then 15.00
when UnitPrice > 15 and UnitPrice < 20 then 25
else UnitPrice
end
答案 1 :(得分:0)
您可以尝试以下声明
Declare @UnitPrice decimal
Declare @ProductId int
Declare UnitPriceUpdateCursore Cursor FOR
Select UnitPrice From Products
OPEN UnitPriceUpdateCursore
Fetch Next From UnitPriceUpdateCursore into @UnitPrice
While (@@Fetch_Status=0)
Begin
select @UnitPrice=UnitPrice from Products where @ProductId=ProductId
IF(@UnitPrice =18.00)
Begin
Update Products set UnitPrice=20 where ProductId=@ProductId
End
ELSE IF(@UnitPrice <25.00)
Begin
Update Products Set UnitPrice=30 Where ProductId=@ProductId
End
Fetch Next From UnitPriceUpdateCursore into @UnitPrice
End
Close UnitPriceUpdateCursore
Deallocate UnitPriceUpdateCursore