I have a table with employee names stored in separate rows like this:
John
Sarah
Mike
What’s the best method to merge these individual names into one combined string that looks like John, Sarah, Mike
? I need to join all the text values from different rows and separate them with commas. Are there any built-in SQL Server functions that can help with this kind of string aggregation? I’ve been trying different approaches but haven’t found a clean solution yet.
interesting question! what sql server version are u using? that’d help me suggest the best approach. also, do u need the names in any particular order, or does any sequence work for you?
u can use FOR XML PATH in older SQL versions. try this: SELECT STUFF((SELECT ', ' + employee_name FROM your_table FOR XML PATH('')), 1, 2, '')
. sounds tricky but it really wrks!
STRING_AGG is your best bet if you’re on SQL Server 2017 or newer. Just use SELECT STRING_AGG(employee_name, ', ') FROM your_table
. It’s built exactly for this - concatenating rows with separators. I’ve found it runs faster than the old FOR XML PATH trick and the code’s way cleaner. Need the names sorted? Add WITHIN GROUP (ORDER BY employee_name)
to STRING_AGG. It beats all the old workarounds and automatically skips null values without any extra work.