s

mssql rows to comma separated string edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 26 September 2020 | 2477

using mssql query how can I convert multiple rows into a comma-separated string. I have a list of countries in my SetupCountry table and I would like to convert the country name into a comma-separated list of countries. Check the query which will return the countries as a comma separated string.

SQL Query

declare @retval varchar(max)
SET @retval = ''
select @retval = @retval   Name   ', ' from SetupCountry order by Name
select @retval

Output

Afghanistan, Albania, Algeria, American Samoa, Andorra, Angola, Anguilla, Antarctica, Antigua And Barbuda, Argentina,