all groups > sql server programming > september 2007 >
You're in the

sql server programming

group:

Is this legal UPDATE syntax? (Running sum calculation)


Is this legal UPDATE syntax? (Running sum calculation) BGL
9/11/2007 10:02:00 PM
sql server programming:
I was looking into ways to calculate running sums in TSQL. (I know, maybe it
belongs in the app, and not in the DB). Self joins and correlated
sub-queries in the SELECT list both work, but they are slow.

Poking around the web I found this interesting UPDATE statement that is able
to produce the running sum.

Is this UPDATE legal? Is this a common construct? It syntactically works,
but it stikes me as similar to the undocumented string concatenation behavior
of string variables in TSQL which are discouraged from being used because
they can be unpredictable.

I'll be ripped a new one by Celko for counting hierarchy nodes like this,
but maybe he can help? :-)

if object_id('tempdb..#temp') is not null
drop table #temp
GO

create table #temp (IndId int identity(1,1),NodeCnt int,RunningSum int,
primary key clustered (IndId))

insert #temp (NodeCnt,RunningSum)
select 0,0 union all
select 3,0 union all
select 11,0 union all
select 3,0 union all
select 7,0
GO

declare @total int
set @total = 0

update #temp
set @total = RunningSum = NodeCnt + @total

select * from #temp

IndId NodeCnt RunningSum
----------- ----------- -----------
1 0 0
2 3 3
3 11 14
4 3 17
5 7 24

(5 row(s) affected)


Re: Is this legal UPDATE syntax? (Running sum calculation) Shiju Samuel
9/11/2007 11:35:08 PM
I _think_ if you don't care about order in which the running total
should be calculated this trick works.

I tried doing an update on a ordered derived table. It doesn't work as
I expected. update is still happening in the unordered set


create table #temp (IndId int ,NodeCnt int,RunningSum int)
--primary key clustered (IndId))


insert #temp
select 1,0,0 union all
select 4,3,0 union all
select 3,11,0 union all
select 2,3,0 union all
select 5,7,0
GO


declare @total int
set @total = 0
update a
set @total = RunningSum = NodeCnt + @total
from
(select top 100 percent
* from #temp
order by indid) a


-
Shiju Samuel


[quoted text, click to view]

Re: Is this legal UPDATE syntax? (Running sum calculation) BGL
9/12/2007 9:26:01 AM
Thanks Shiju, nice example to illustrate the behavior.

[quoted text, click to view]
Re: Is this legal UPDATE syntax? (Running sum calculation) Anith Sen
9/12/2007 1:40:37 PM
[quoted text, click to view]

It is often called t-SQL update extension which is syntactically supported.
However, you are correct in that is suffers from the same drawbacks of the
undocumented string concatenation behavior when applied across a set of
rows. For instance, simply changing the underlying indexes' ordering has
shown to give unpredictable results.

--
Anith

AddThis Social Bookmark Button