TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
How to get column values to comma separated value in SQL
Punit Jain
Jan 03
2015
Code
2
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
--Create sample table
Create
Table
#
Temp
(
PkValue
int
)
--Insert sample data
Insert
Into
#
Temp
Values
(1)
Insert
Into
#
Temp
Values
(2)
Insert
Into
#
Temp
Values
(3)
Insert
Into
#
Temp
Values
(1)
Insert
Into
#
Temp
Values
(2)
Insert
Into
#
Temp
Values
(3)
--Declare and initialise variable
Declare
@Ids nvarchar(
max
)
Set
@Ids =
''
--Get distinct comma seperated values into variable
Select
@Ids = (@Ids +
Coalesce
(
Case
when
CHARINDEX(
Convert
(nvarchar(
max
),PkValue) +
','
,@Ids) > 0
Then
''
Else
convert
(nvarchar(
max
),PkValue)+
','
End
,
''
))
From
#
Temp
--Verify output with sample data used
Select
@Ids
Select
*
From
#
Temp
--Drop sample table
Drop
Table
#
Temp
Comma separated values in SQL
CSV in SQL