1

TempTable has columns RunningTotal and ClientCount, we also have @RunningTotal variable declared and set to 0.

Can someone please explain what does this line do ?

UPDATE Temptable 
SET @RunningTotal = RunningTotal = @RunningTotal + ClientCount
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ilya_i
  • 333
  • 5
  • 14
  • i think update the variable (@)RunningTotal and the field of the table together with this value (@)RunningTotal + ClientCount – Mattia Caputo Oct 02 '15 at 11:04

1 Answers1

1

Never seen this construct before, but it seems to work like this. It fills column RunningTotal with a cumulative total of ClientCount.

Say we start with a table with just ClientCount filled in:

CREATE TABLE dbo.Temptable (ClientCount int, RunningTotal int)
INSERT INTO Temptable (ClientCount) VALUES (5), (4), (6), (2)
SELECT * FROM Temptable

ClientCount RunningTotal
----------- ------------
5           NULL
4           NULL
6           NULL
2           NULL

And then run the update statement:

DECLARE @RunningTotal int = 0
UPDATE Temptable SET @RunningTotal = RunningTotal = @RunningTotal + ClientCount
SELECT * FROM Temptable

ClientCount RunningTotal
----------- ------------
5           5
4           9
6           15
2           17

As you can see, each value of RunningTotal is the sum of all ClientCount values from the current and any preceding records.

The downside is, you have no control in which order the records are processed. Which makes me wonder whether this is a recommended approach in a production environment.

Please check here for a deeper discussion: Calculate a Running Total in SQL Server

Ruud Helderman
  • 10,563
  • 1
  • 26
  • 45