Click here to Skip to main content
15,891,529 members
Articles / Programming Languages / SQL
Alternative
Tip/Trick

Get Column values as comma seperated string

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
13 Apr 2012CPOL 17.6K   7   3
Another option:declare @commaStringList varchar(max)set @commaStringList = ''select @commaStringList = @commaStringList + ', ' + CAST(ColumnName as VARCHAR) from MyTable -- remove leading commentif len(@commaStringList) > 3 set @commaStringList =...
Another option:
 
SQL
declare @commaStringList varchar(max)
set @commaStringList = ''
select @commaStringList = @commaStringList + ', ' +
       CAST(ColumnName as VARCHAR) from MyTable 
 

-- remove leading comment
if len(@commaStringList) > 3
  set @commaStringList = substring(@commaStringList, 3, len(@commaStringList) - 2)
 
-- show the result
select @commaStringList

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) The Code Project
United States United States
Elina joined the Code Project team as a software developer in order to make the site run even smoother than it is now. She will also take care of making wishes and promises on the site improvements come to the light sooner than later. When not at work, she enjoys being with her family and wishes there will be at least 30 hours in a day Smile | :)

Comments and Discussions

 
GeneralYou are right, typo fixed. (and improved a bit) Pin
Elina Blank11-Jun-10 5:49
sitebuilderElina Blank11-Jun-10 5:49 
GeneralReason for my vote of 1 Does not work. Pin
Manas Bhardwaj11-Jun-10 5:47
professionalManas Bhardwaj11-Jun-10 5:47 
GeneralDoen't work buddy. Btw, I tested in SQL Server 2005. Pin
Manas Bhardwaj11-Jun-10 5:47
professionalManas Bhardwaj11-Jun-10 5:47 
Doen't work buddy. Btw, I tested in SQL Server 2005.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.