sql-server - 在 SQL Server 2008 中使用条件更新行

标签 sql-server sql-server-2008

这是我的表结构:

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/

相关文章:

sql-server - 创建 MSSQL 存储过程以检查 TableA 记录计数。然后将 TableA 记录插入到 TableB

sql-server - SQL 将多条记录合并为一行

sql-server - 如何找到连接字符串的 ODBC 驱动程序名称?

sql-server - 什么是命名管道?

sql - 唯一标识符 PK : Is a SQL Server heap the right choice?

sql - 如何检查给定的字符串是sql server中的保留关键字

sql-server - SQL Server BCP 导出损坏的文件?

sql-server - 为什么DATETIME可以减整数,但DATE类型不能减

xml - 使用 xquery 从 xml 中提取数据的最佳方法

sql - 同时替换多个值 - 以便将字符串转换为数字