Wednesday, September 10, 2014

SQL Query Column values as comma separated



Introduction


I have a table as shown below, which has Country_Code and Cities of the a country.

 I need to retrieve distinct cities in a country based on the Country_Code
column as a comma separated string.



SQL Statement


The following SQL Statement shows how it can be achieved

Begin
declare @str varchar(1000)

SELECT @str= coalesce(@str + ',' , '') + a.CountryLang_Desc 
FROM (SELECT DISTINCT CountryLang_Desc from CountryLanguages where Country_Code='IN') a

print @str 
End