Twitter

Follow SQLQuill on Twitter

Subscribe

MN Pass

TSQL Tip O’ the Week – 7/26/11 – A Column to CSV

This weeks tip:

Recently I needed to convert a column to a file of comma separated values (CSV).  There are a few ways to do this via TSQL, here’s a simple one – use COALESCEThe idea is to declare a variable, set it equal to itself and a comma and the next data value, finally select the variable. See the example as it’s much easier to follow.

The Setup:

Create table CSVTest (Name varchar(50))
GO
Insert CSVTest Values('Andy Lohn'),
('Adrian Lohn'),
('Maggie Lohn'),
('Nala Lohn')
Go
Select Name from CSVTest
Go

This returns, as expected the following:

Results20110725

The Example:

Declare @Names varchar(2000)
Select @Names = Coalesce(@Names + ', ','') + Name from CSVTest
Select @Names as 'CSV List'

This returns the same results, except in as a comma separated list instead of a column.

Results20110725_2

Here are some related posts from the intraweb – including other ways to do this with user defined functions and XML:

Previous Tips O’ the Week

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>