Recently I had the necessity to retrieve a concatenated string of values as a column for a report. This can be achieved quite simply by creating a UDF that returns the concatenated string and calling within the SELECT statement.
However, I do not like using UDF’s within SELECT statements due to performance issues. So I started searching the net for a possible alternative and came across the following:
http://www.kodyaz.com/articles/concatenate-using-xml-path.aspx
Now I have never used the SQL STUFF function or XML Path clause but the combination of the two enabled me to achieve my goal very quickly.
SELECT TOP 1
STUFF(
(
SELECT ', ' + Username
FROM Users
FOR XML PATH('')
), 1, 1, ''
) As ListOfUsers
From Users