I think that this is brilliant! I found this solution on SQL Authority’s site:
http://blog.sqlauthority.com/2009/11/25/sql-server-comma-separated-values-csv-from-table-column/
It is the most unique way of building a comma separated list in SQL that I have seen. Most methods, and the ones I have used before as well, required building a user-defined function in SQL. This one is unique in that it is:
1. Simple
2. can be used inline, in the SELECT statement.
Nice! Thank you Pinal Dave!
For reference, his example code is :
SELECT SUBSTRING(
(SELECT ',' + s.ColumnName
FROM TableName s
ORDER BY s.ColumnName
FOR XML PATH('')),2,200000) AS CSV
GO
For me, I added it inline to a SELECT statement.
SELECT
u1.UserId,
u1.Department,
u1.EmployeeID,
u1.ReportsTo as [Manager Name],
(
SELECT SUBSTRING(
(SELECT ',' + s.PhoneNumber
FROM UserPhones s
WHERE s.UserID=u1.UserId and PhoneStatus='Active'
ORDER BY s.UserId, s.PhoneNumber
FOR XML PATH('')),2,1000) AS CSV
) as ActivePhoneNumbers
FROM Users as u1