June 2008
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          
Search

 
Catagories
Archives
Recent Entries
Links
RSS
pivot row into a comma delimited list
Catagory: sql server · This Entry · Comment(1) · eMail entry · Google
April 21, 2005 02:31 PM

sql server

ok, whoa, just picked this one up. usually variable assignment from a select statement is thought of as returning one final *single* value (whatever that happens to be).

if instead you perform some logical operations a variable in the meantime you can also continuously calculate and update a variable based on each subsequent row returned.


here's a simple example with simple math...

create table test
(
a int
)

insert into test values (1)
insert into test values(4)
insert into test values(10)

declare @a int
select @a = 0
select @a = @a + a from test

select @a

returns "15"

you have to mind the first value returned, to make sure your statement evaluates as desired (using nulls or not). alright here's something useful -- this process makes concatenating column data into a single line easy (think enumerated list of comma delimited values). here's how...

-- this statement concatenates rows into a single value
-- by performing a variable assignment (for each row returned).

-- assuming you have a table w/ column "col1" as varchar here...

declare @x varchar(1000)

-- make this null if needed
-- this forces COALESCE to skip the comma on the first row.
set @x= null

select @x = COALESCE(@x + ', ', '') + CAST(col1 AS varchar(1000))
from MyTable where col1 is not null and len(col1)>0

select @x

so you've just 'pivoted' the column data from col1 into a single (comma delimited) row. rather handy when needed, and you can forgo using a cursor.





Comments

Thank you so much for that. I was starting to consider really silly ways of achieving the same result...

Posted by paulstrovsky at February 8, 2006 02:22 PM


Post a comment
Name:


Email Address:


URL:


Comments: