Asp.net blogs

Friday, 7 March 2014

Query to generate comma-separated list from one individual column data from database table in sql server

Table Name > EmployeeDetails
           Fields >  EmployeeName
             Data > Rohin
                          Rajat
                          Rahul
                          Ishan

Query to generate comma-separated list from one individual column data from database table in sql server

Query >
SELECT STUFF((SELECT ',' + [EmployeeName]
              FROM @EmployeeDetails
              ORDER BY [EmployeeName]
              FOR XML PATH('')), 1, 1, '') AS [EmployeeName]

Output
Ishan,Rahul,Rajat,Rohin