Skip to content
Advertisement

Combine multiple results into a single string in SQL Server

Is it possible to combine multiple results into a single string in SQL Server?

I have the following table:

NameID Name
------ -----
1      Alvin
2      Alan
3      Ben
4      Tom

How can I select the table and return the select result as below:

Group
-----
Alvin, Alan, Ben and Tom

Advertisement

Answer

Try this:

  SELECT
  SUBSTRING((SELECT
    ',' + CAST(Name AS varchar)
  FROM table_name
  FOR xml PATH (''))
  , 2, 10000) AS Group1

enter image description here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement