Shortest code to get comma separated values from a column

Getting results of a column in comma separated format is often required while one is writing the stored procedure. The comma separated values then can be used in SQL ‘In’ clause to filter the result. Below example will show you how to get values of a column in comma separated format:

Suppose you have a table named ‘tblCountry’ with following data:Untitled

Now you want your countries to be in comma separated format likeĀ India,Australia,US,UK.

Following snippet will give you the desired result:

DECLARE @SQL nvarchar(MAX)
SELECT @SQL = COALESCE(@SQL + ‘,’,”) + CountryName FROM [dbo].[tblCountry]
SELECT @SQL

The result is a string of characters that can be used further in the code.

Enjoy! Happy Coding!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s