Question : How to turn table values into a comma separated list?

Hi,
  I need a code to convert temp table rows into a single comma separated list.
  Please let me know how we can do that.

Example : I have a table T, that has rows like :
T
A
B
C
D

I need some code to make these rows into a single list "A,B,C,D".

Thanks!
 

Answer : How to turn table values into a comma separated list?

You want all of the rows' values into a single string? What's the maximum size? What Sybase database product and version are you running?

If this is Sybase ASE, the "obvious" way to do this would be with a cursor that basically does a WHILE loop through the rows, incrementally concatenating a string. If you have 10 or fewer rows this won't be too painfully slow, but there are faster ways.

You might hope that we could use a SELECT to update a local variable for each row in the SELECT's result set. Unfortunately that doesn't work, as variable assignments in SELECTs (in Sybase ASE) are performed only on the last row. But you can do a weird thing with an UPDATE... because UPDATES are processed for each row:

declare @string varchar(10000)
update
set @string=@string+n>+", "    -- you might need to convert to a varchar here
, =
select @string

Note this does actually update every row in the table. If you have millions of rows you might fill the transaction log.

This also places a ", " at the end of every row's value. You can get rid of the final terminating one by replacing the last line above with:

select reverse(substring(reverse(@string), 3, 10000))
Random Solutions  
 
programming4us programming4us