Home Forums SQL Server 2008 T-SQL (SS2K8) Seems like a simple problem. Need to decrease an Amt by a fixed maximum spread over several rows. RE: Seems like a simple problem. Need to decrease an Amt by a fixed maximum spread over several rows.

  • Have you tried the Quirky Update? It's explained in the following article: http://www.sqlservercentral.com/articles/T-SQL/68467/

    Be sure to understand it, follow the rules and test it correctly.

    Here's an idea using your sample tables.

    declare @tbl table

    (LineNum int PRIMARY KEY CLUSTERED,

    Code varchar(2),

    Amt money,

    MaxAmt money

    )

    insert into @tbl (LineNum, Code, Amt, MaxAmt)

    values

    (1,'AA',10.00,50.00),

    (2,'AA',20.00,50.00),

    (3,'AA',10.00,50.00),

    (4,'AA',40.00,50.00)

    DECLARE @Amt money = 0,

    @AcumAmt money = 0

    UPDATE t SET

    @Amt = Amt = CASE WHEN @AcumAmt + Amt < MaxAmt THEN Amt

    WHEN MaxAmt - @AcumAmt < 0 THEN 0

    ELSE MaxAmt - @AcumAmt END,

    @AcumAmt = @AcumAmt + Amt

    FROM @tbl t

    OPTION (MAXDOP 1)

    SELECT *

    FROM @tbl

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2