Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
How to get column values to comma separated value in SQL
WhatsApp
Punit Jain
Jan 03
2015
2.1
k
0
0
--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
Up Next
How to get column values to comma separated value in SQL