mssql rows to comma separated string Edit

Murugan Andezuthu Dharmaratnam | 26 September 2020 | 641

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,