我有一个简单的表来存储库存水平。即。
ID int PK
LocationID int
StockLevel real对于每个位置,此表中可能有多个行,即:
ID | LocationID | StockLevel
----------------------------
1 | 1 | 100
2 | 1 | 124
3 | 2 | 300在本例中,位置1处存在224个单元,这是微不足道的。
当我开始递减位置1处的库存水平时,我使用游标遍历LocationID为1的所有行,并使用一些简单的逻辑来确定当前行上可用的库存是否满足传递的减量值。如果行有足够的数量来满足需求,我会递减rows值并退出游标,然后结束该过程;但是,如果行没有足够的可用数量,我会将其值递减为零,然后移动到下一行,然后重试(减少的数量)
它非常简单,工作正常,但不可避免的问题是:有没有一种方法可以在没有光标的情况下执行这个RBAR操作??我已经尝试过寻找替代方案,但即使是这样的操作的搜索标准也是令人痛苦的!
先谢谢你尼克
ps。我以这种格式存储数据,因为每一行还包含其他唯一的列,因此不能简单地为每个位置聚合到一行中。
pps。根据请求的光标逻辑(其中'@DecrementStockQuantityBy‘是我们需要在指定位置减少库存水平的数量):
WHILE @@FETCH_STATUS = 0
BEGIN
IF CurrentRowStockStockLevel >= @DecrementStockQuantityBy
BEGIN
--This row has enough stock to satisfy decrement request
--Update Quantity on the Current Row by @DecrementStockQuantityBy
--End Procedure
BREAK
END
IF CurrentRowStockStockLevel < @DecrementStockQuantityBy
BEGIN
--Update CurrentRowStockStockLevel to Zero
--Reduce @DecrementStockQuantityBy by CurrentRowStockStockLevel
--Repeat until @DecrementStockQuantityBy is zero or end of rows reached
END
FETCH NEXT FROM Cursor
END希望这够清楚了吧?如果需要更多/更好的解释,请让我知道。谢谢
发布于 2011-07-14 19:21:08
您是对的,先生,在这种情况下,一个简单的update语句可以帮助您,我仍然在尝试为游标找到一个合法的用法,或者当我不能用CTE或基于set来解决这个问题时。
在深入研究您的问题之后,我还将提出一个替代解决方案:
Declare @LocationValue int = 1,@decimentvalue int = 20
with temp (id,StockLevel,remaining) as (
select top 1 id, Case when StockLevel - @decimentvalue >0 then
StockLevel = StockLevel - @decimentvalue
else
StockLevel = 0
end, @decimentvalue - StockLevel
from simpleTable st
where st.LocationID = @LocationValue
union all
select top 1 id, Case when StockLevel - t.remaining >0 then
StockLevel = StockLevel -t.remaining
else
StockLevel = 0
end, t.remaining - StockLevel
from simpleTable st
where st.LocationID = @LocationValue
and exists (select remaining from temp t
where st.id <> t.id
group by t.id
having min(remaining ) >0) )
update st
set st.StockLevel = t.StockLevel
from simpleTable st
inner join temp t on t.id = st.idhttps://stackoverflow.com/questions/6692152
复制相似问题