我额头上的标记从墙上变得太红了,所以张贴听到......
我有两个表,需要根据另一个表的选择标准更新一个表。我知道我可以使用“where exists”的更新,但我有很多循环更新。所以我试图使用游标将一个表中的值放入变量,然后使用这些变量在另一个表上使用更新。没有发生错误,也没有更新。当我将代码更改为Select语句时,它会正确显示信息,但更新不起作用。我不确定它是否基于使用“for update”创建游标,因为我正在更新的表与光标从中选择记录的表不同。以下是我的查询。有人请告诉我我可能做错了什么。谢谢!
DECLARE @so VARCHAR(50)
DECLARE @line VARCHAR(50)
DECLARE @pdate DATETIME
DECLARE @reason1 VARCHAR(50)
DECLARE @reason2 VARCHAR(50)
DECLARE @area VARCHAR(50)
DECLARE mycursor CURSOR FOR
SELECT [bp_so_number],[bp_line],[bp_production_date],[bp_reason1],[bp_reason2],[bp_area]
FROM [Workflow].[dbo].[v_OTD_PostSrc]
OPEN mycursor
FETCH NEXT FROM mycursor
INTO @so, @line, @pdate, @reason1, @reason2, @area
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM mycursor
INTO @so, @line, @pdate, @reason1, @reason2, @area;
UPDATE otd_data SET reason1=@reason1, reason2=@reason2, area=@area
WHERE [Order Number]=@so AND LI=@line AND [Schedule Date]=@pdate AND [Qty Open]>0
--SELECT * FROM otd_data WHERE [Order Number]=@so AND LI=@line AND [Schedule Date]=@pdate
END
CLOSE mycursor
DEALLOCATE mycursor
像我说的那样。没有错误,也没有表更新......: - (
答案 0 :(得分:1)
您在首次更新前进行两次抓取。尝试将循环重构为:
DECLARE @so VARCHAR(50)
DECLARE @line VARCHAR(50)
DECLARE @pdate DATETIME
DECLARE @reason1 VARCHAR(50)
DECLARE @reason2 VARCHAR(50)
DECLARE @area VARCHAR(50)
DECLARE mycursor CURSOR LOCAL FAST_FORWARD FOR
SELECT [bp_so_number],[bp_line],[bp_production_date],[bp_reason1],[bp_reason2],[bp_area]
FROM [Workflow].[dbo].[v_OTD_PostSrc]
OPEN mycursor
-- Always true
WHILE 1 = 1
BEGIN
-- Get next record from cursor
FETCH NEXT FROM mycursor
INTO @so, @line, @pdate, @reason1, @reason2, @area;
-- If there was a record @@fetch_status will be 0;
-- if not, or in case of an error, break the loop
IF @@FETCH_STATUS <> 0
break
UPDATE otd_data SET reason1=@reason1, reason2=@reason2, area=@area
WHERE [Order Number]=@so AND LI=@line AND [Schedule Date]=@pdate AND [Qty Open]>0
--SELECT * FROM otd_data WHERE [Order Number]=@so AND LI=@line AND [Schedule Date]=@pdate
END
CLOSE mycursor
DEALLOCATE mycursor
我在游标中添加了LOCAL and FAST_FORWARD个选项。有关FAST_FORWARD的文档:
指定具有性能的FORWARD_ONLY,READ_ONLY游标 已启用优化。