假设我spCalculate
以@amount
作为参数。
我有STOCK
表,其中包含以下行
----------------
STOCKID | AMOUNT
----------------
1 | 50
2 | 70
3 | 20
spCalculate将从AMOUNT
减去STOCK
,直到@amount
值达到零。例如,如果@amount
为100
,则最终结果为
----------------
STOCKID | AMOUNT
----------------
1 | 0
2 | 20
3 | 20
如果@amount
是30
,那么
----------------
STOCKID | AMOUNT
----------------
1 | 20
2 | 70
3 | 20
如果@amount
是130
,那么
----------------
STOCKID | AMOUNT
----------------
1 | 0
2 | 0
3 | 10
如何在不循环的情况下实现这一目标?
答案 0 :(得分:3)
使用CROSS APPLY
:
UPDATE s
SET AMOUNT = CASE
WHEN r IS NULL THEN
CASE
WHEN amount - @amount < 0 THEN 0
ELSE amount - @amount
END
WHEN AMOUNT - r < 0 THEN 0
ELSE AMOUNT - r
END
FROM STOCK s
CROSS APPLY(
SELECT r = @amount - SUM(AMOUNT)
FROM STOCK
WHERE STOCKID < s.STOCKID
)x
WHERE R IS NULL OR R > 0