Monday, February 1, 2010

Creating delimited list using TSQL


If you've ever needed to create a delimited list from a single column of data stored in SQL Server and felt like it required unnecessary arm wrestling due to SQL syntax limitations, this could be handy for you next time, too:

Let's say you have a column called "lastName" and want to get a comma-delimited list of last names. Here's a way:

-- set up a var for the list

declare @list varchar(1000)
set @list = ''


-- create the delimited list using a query

select @list = @list + lastName + ', ' from person

-- trim off the trailing comma and space if necessary

if @list <> '' set @list = left(@list, len(@list) - 1)

-- take a look at the results

print @list

Here are some example results:

Rubble, Flintstone, Jetson, Munster

Neat trick.