Create comma seperated list out of a sql query ( tsql )

Surfing the net for a sql answer, I came across something really cool. Below is an example of how to create a comma separated list of values in a single query.

–declare holder var
DECLARE @list VARCHAR(8000)

–build comma separated list
SELECT @list = COALESCE(@list + ‘, ‘, ”) + CAST(track_id AS VARCHAR(5) )
FROM webtool_tracks

–show results
SELECT @list AS ‘list’

The results should look something like this


About Eric Fickes

Independent Internet Consultant by day. Skateboarder, Bass player, Husband and Father by night. You can hire me to build internet powered solutions
This entry was posted in fun, microsoft, SQL and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>