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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Uttam KumarPosted Mar 30, 2022, 8:27 AM
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
Sachin SinghPosted Mar 29, 2022, 9:53 AM
Jignesh KumarPosted Mar 29, 2022, 7:07 AM
Muhammad Imran AnsariPosted Mar 29, 2022, 4:58 AM