这是我的表结构:
CREATE table Credit(id integer, organisationid int, availableCredit int)
INSERT INTO Credit VALUES (1, 1, 1000)
INSERT INTO Credit VALUES (2, 1, 100)
INSERT INTO Credit VALUES (3, 2, 600)
INSERT INTO Credit VALUES (4, 2, 400)
我必须减少可用信用栏值,我身上有金额 1050。我需要从组织 id = 1 的信用表中减少 1050。这里组织 ID 1 总共有 1100 可用信用。条件是应首先更新第一个插入的信用行,然后再更新其余行(先进先出模型),并且更新应仅在organizationId = 1时发生。
我们如何使用单个或多个更新语句来更新它?
有什么建议吗?
最佳答案
不幸的是,在 T-SQL 中这是一件相当困惑的事情 - 您需要类似循环的东西(游标或 WHILE
语句)。
有了这里的代码,我可以让它运行 - 它不太漂亮,但它可以工作。
-- you want to reduce the total credits by this amount
DECLARE @AmountToReduce INT = 1050
-- temporary variables
DECLARE @ID INT, @AvailableCredit INT
-- get the first row from dbo.Credit that still has availableCredit - ordered by id
SELECT TOP 1 @ID = id, @AvailableCredit = availableCredit
FROM dbo.Credit
WHERE availableCredit > 0 AND organisationId = 1
ORDER BY id
-- as long as we still have credit to reduce - loop..
WHILE @AmountToReduce > 0 AND @ID IS NOT NULL
BEGIN
-- if we need to remove the complete availableCredit - do this UPDATE
IF @AmountToReduce > @AvailableCredit
BEGIN
UPDATE dbo.Credit
SET availableCredit = 0
WHERE id = @ID
SET @AmountToReduce = @AmountToReduce - @AvailableCredit
END
ELSE BEGIN
-- if the amount to reduce left is less than the availableCredit - do this UPDATE
UPDATE dbo.Credit
SET availableCredit = availableCredit - @AmountToReduce
WHERE id = @ID
SET @AmountToReduce = 0
END
-- set @ID to NULL to be able to detect that there's no more rows left
SET @ID = NULL
-- select the next "first" row with availableCredit > 0 to process
SELECT TOP 1 @ID = id, @AvailableCredit = availableCredit
FROM dbo.Credit
WHERE availableCredit > 0 AND organisationId = 1
ORDER BY id
END
关于sql-server - 在 SQL Server 2008 中使用条件更新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11647824/