One problem with that technique (@variable = column = expression ) to update a table with a running total is that the updates don't happen in any specific order.One way to solve that is to pre-create #temp with a clustered primary key on the column you want to order the total by. The updates will more likely occur in that order:if object_id('tempdb..#temp') > 0 drop table #tempcreate table #temp (intTransactionID int primary key clustered ,fltAmount float ,RunningTotal float)--Your sample datainsert #temp (intTransactionID, fltAmount, RunningTotal)select intTransactionID, fltAmount, RunningTotalfrom ( select 10 intTransactionID, 10000009.0 fltAmount, 0 RunningTotal union all select 11, 500000.45000000001, 0 union all select 7, 10000009.0, 0 union all select 8, 500000.45000000001, 0 union all select 5, 10000009.0, 0 union all select 6, 500000.45000000001, 0 union all select 9, 10000009.0, 0 union all select 12, 500000.45000000001, 0 union all select 16, 10000009.0, 0 union all select 15, 500000.45000000001, 0 union all select 14, 10000009.0, 0 union all select 13, 500000.45000000001, 0 union all select 4, 10000009.0, 0 union all select 20, 500000.45000000001, 0 union all select 19, 10000009.0, 0 ) adeclare @RunningTotal floatset @RunningTotal = 0UPDATE #Temp SET @RunningTotal = RunningTotal = @RunningTotal + fltAmountselect * from #temp order by 1OUTPUT:intTransactionID fltAmount RunningTotal ---------------- ----------------------------------------------------- ----------------------------------------------------- 4 10000009.0 10000009.05 10000009.0 20000018.06 500000.45000000001 20500018.4499999997 10000009.0 30500027.4499999998 500000.45000000001 31000027.8999999999 10000009.0 41000036.89999999910 10000009.0 51000045.89999999911 500000.45000000001 51500046.35000000112 500000.45000000001 52000046.80000000413 500000.45000000001 52500047.25000000714 10000009.0 62500056.25000000715 500000.45000000001 63000056.7000000116 10000009.0 73000065.70000001819 10000009.0 83000074.70000001820 500000.45000000001 83500075.150000021
Be One with the OptimizerTG