How to get comma separated values.
Loading
How to get comma separated values.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Mar 29, 2022, 12:58 AM EDT
Jignesh KumarRank #91 · 22.9K reputationPosted Mar 29, 2022, 3:07 AM EDT
Sachin SinghRank #66 · 26.2K reputationPosted Mar 29, 2022, 5:53 AM EDT
Uttam KumarRank #1,076 · 1.8K reputationPosted Mar 30, 2022, 4:27 AM EDT
There are 3 ways to do this. You can try one by one and choose the one you like it.
1. Concat Rows using COALESCE
Select EmpName from Employee;
Declare @val Varchar(MAX);
Select @val = COALESCE(@val + ', ' + EmpName, EmpName) from Employee
Select @val;
2. Concat Rows using FOR XML PATH
To remove the leading comma:
Select SUBSTRING(
(
Select ', ' + EmpName As 'data()' from Employee FOR XML PATH('')
), 2, 9999) As Employees
If you don't need the trailing space and just want a comma along a separator, then remove the data() function:
Select Employees = STUFF((
Select ', ' + EmpName from Employee FOR XML PATH('')), 1, 1, '')
3. Concat Rows using STRING_AGG
NOTE: This is available from SqlServer 2017 onwards
Select STRING_AGG(ISNULL(EmpName, ' '), ',') As Employees from Employee