是否有可能基于param减去我的表行值,直到它在没有循环的情况下达到零?

时间:2015-07-28 03:03:53

标签: sql sql-server sql-server-2008 tsql

假设我spCalculate@amount作为参数。

我有STOCK表,其中包含以下行

----------------
STOCKID | AMOUNT
----------------
      1 |     50
      2 |     70
      3 |     20

spCalculate将从AMOUNT减去STOCK,直到@amount值达到零。例如,如果@amount100,则最终结果为

----------------
STOCKID | AMOUNT
----------------
      1 |      0
      2 |     20
      3 |     20

如果@amount30,那么

----------------
STOCKID | AMOUNT
----------------
      1 |     20
      2 |     70
      3 |     20

如果@amount130,那么

----------------
STOCKID | AMOUNT
----------------
      1 |      0
      2 |      0
      3 |     10

如何在不循环的情况下实现这一目标?

1 个答案:

答案 0 :(得分:3)

使用CROSS APPLY

SQL Fiddle

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