Search code examples
sqlsql-serverrunning-balance

How to update running balance in one shot?


I have a temp table, let's call it #invoices, defined as

create table (id int identity(1, 1), billed money, credited money, balance money)

i have the following data in it

Billed   Credited
140.00   
20.00
          60.00
          20.00
         -20.00

I would like to update the balance column with the running balance. so that the Balance column is updated properly. Balance is basically, Billed - Credited, but has to take into the account the previous row.

So in my example, the Balance will be so:

Billed   Credited  Balance
140.00              140.00
20.00               160.00
          60.00     100.00
          20.00      80.00
         -20.00    -100.00

Is there a way to do this without looping through the rows and keeping the running balance? Basically I am looking to update the Balance column in a set-based way.


Solution

  • There are set-based ways to calculate running totals in SQL Server, however in the current versions of SQL Server a cursor-based solution is often quicker.

    Adam Machanic wrote a great article on it here.