Thursday 1 January 2015

Shortest code to get comma separated values from a column

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

No comments:

Post a Comment