SQL Columns to CSV List

There have been a few times where I’ve needed to return the values of multiple columns as one column containing a CSV list of those values.

This is accomplished using a sub-query like so…

USE AdventureWorks
GO
-- Check Table Column
SELECT Name
FROM HumanResources.Shift
GO
-- Get CSV values
SELECT STUFF(
(SELECT ',' + s.Name
FROM HumanResources.Shift s
ORDER BY s.Name
FOR XML PATH('')),1,1,'') AS CSV
GO

The above example came from Pinal Dave’s great post on SQL Authority. I substituted his use of SUBSTRING for STUFF since it will handle any length content.



, ,

One Comment to “SQL Columns to CSV List”

  1. Madryt says:

    I have to voice my passion for your generosity supporting individuals that actually need help on in this subject. Your special commitment to passing the message around has been astonishingly useful and have continuously empowered somebody like me to attain their goals. Your amazing valuable tips and hints signifies much to me and still more to my office colleagues. Warm regards; from each one of us.

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>

This entry was posted on February 6, 2013 and is filed under SQL. Written by: . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.