Skip to content
Advertisement

How do I calculate a running total in SQL without using a cursor?

I’m leaving out all the cursor setup and the SELECT from the temp table for brevity. Basically, this code computes a running balance for all transactions per transaction.

Inspired by this code from an answer to another question,

I was wondering if SQL had the ability to sum numbers in the same way it’s concatonating strings, if you get my meaning. That is, to create a “running balance” per row, without using a cursor.

Is it possible?

Advertisement

Answer

You might want to take a look at the update to local variable solution here: http://geekswithblogs.net/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005—the-optimal.aspx

Outperforms all other methods, but has some doubts about guaranteed row order. Seems to work fine when temp table is indexed though..

  • Nested sub-query 9300 ms
  • Self join 6100 ms
  • Cursor 400 ms
  • Update to local variable 140 ms
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement