Friday, May 28, 2010

Concatenating String Fields In T-SQL

Lets say you've got a table called 'metaproperty' with an NVARCHAR(50) field called 'names'. How do you get all the values of the 'names' field concatenated into one string, separated by commas?

Like this:

select STUFF(
(SELECT N',' + names
FROM (SELECT * FROM metaproperty) AS Y
--ORDER BY names
1, 1, N'')

The ORDER BY is optional, as are any DISTINCTs you might want to shove in...

No comments:

Post a Comment