Click here to Skip to main content
15,886,664 members
Articles / Database Development / SQL Server
Tip/Trick

SQL: Column Values as Comma Separated String

Rate me:
Please Sign up or sign in to vote.
4.88/5 (6 votes)
10 Aug 2013CPOL 104.4K   6   2
Column values as comma separated string in SQL

Introduction

I have a table as shown below, which has Country_Code and languages that are spoken by different people living in a country. I need to retrieve distinct languages spoken in a country based on the Country_Code column as a comma separated string.

SQL Statement

The following statement shows how it can be achieved:

SQL
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 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Program Manager
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questioncoalesce query Pin
Tirthankar Dey1-Sep-13 21:24
Tirthankar Dey1-Sep-13 21:24 
QuestionWhat about NULL values? Pin
Konstantin Taranov15-Aug-13 23:47
professionalKonstantin Taranov15-Aug-13 23:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.