Saturday, June 28, 2014

SQL statement that selects a column from a table and converts the results to a comma separated string?

I have a column EmpID in Employee table as shown below


EmpID
E01
E03
E05
E09

Solution:

DECLARE @results VARCHAR(500)

SELECT 
    @results = COALESCE(@results + ',', '') + CONVERT(VARCHAR(12),EmpID)
FROM
    Employee
ORDER BY
    EmpID

SELECT @results AS RESULTS

RESULTS
E01,E03,E05,E09