sql-server - 更新临时表后,while循环未选择所需的记录
问题描述
我有一个嵌套的 while 循环来从 #stock 表中选择一些股票记录。如果库存耗尽,我需要移动到下一个匹配的库存记录。我的循环不断从临时表中选择同一行。即使我删除了该行,并在嵌套的 Begin...End 中进行验证。
WHILE @DemandOutstandingQty > 0 --Check for stock
BEGIN
SET ROWCOUNT 1
SELECT @StockExpirationDate = ExpirationDate, @StockRemainingQty = RemainingQty, @StockLotNum = LotNum, @StockID = StockGUID
FROM #stock WHERE PartNum = @DemandPartNum AND RemainingQty > 0
ORDER BY ExpirationDate ASC
WHILE @StockID IS NOT NULL
BEGIN
SET ROWCOUNT 0
--several other if blocks here end with demand going to 0 and breaking to the outer While
IF (@StockExpirationDate > @DemandDueDate AND @StockRemainingQty < @DemandOutstandingQty) --Stock not enough to meet demand
BEGIN
UPDATE #Stock SET RemainingQty = 0 WHERE StockGUID = @StockID;
--DELETE FROM #stock WHERE StockGUID = @StockID; --Tried this also
SET @DemandOutstandingQty = @DemandOutstandingQty - @StockRemainingQty;
Print @@StockID --The stock record with no remaining stock or deleted
Select * from #stock where StockGUID = @StockID; --returns no rows / updated remaining qty
END;
SET ROWCOUNT 1
SELECT @StockExpirationDate = ExpirationDate, @StockRemainingQty = RemainingQty, @StockLotNum = LotNum, @StockID = StockGUID
FROM #stock
WHERE PartNum = @DemandPartNum AND RemainingQty > 0 AND StockGUID <> @StockID
ORDER BY ExpirationDate ASC
Print @StockID --Its the same ID, not moving to the next stock record
SET ROWCOUNT 0
END --@StockID while
--does some more stuff
END --Outer While
这可能是因为嵌套的 Begin...End 吗?
解决方案
解决。
切换到 WHILE @StockRemainingQty > 0 作为条件,并在库存用完时设置 '@StockRemainingQty = 0。
感谢HABO的提醒。@stockID 没有改变。
推荐阅读
- strapi - 如何使用 HTTP 请求更改 Strapi 条目?
- github - 多分支管道。无法配置特定的分支配置
- node.js - 我的 nodejs 电子打包器说警告错误
- javascript - 如何将页面部分锚定到滚动显示的导航栏底部?
- python - 尝试使用 xpath 查找元素时收到错误消息“没有这样的元素:无法找到元素”
- r - TramineR 中的集群命名和标签
- scheduled-tasks - 重新运行成功的 oozie 作业
- javascript - Node.js 模块是单例吗?
- getstream-io - GetStream 中的唯一记录是什么意思?
- python - 文本中单词的频率(熊猫)