Get all the values of a single column in a variable

Lakhangarg
Posted by Lakhangarg under Sql Server category on | Views : 2789
Get all the values of a single column in a variable separated by comma.
DECLARE a Variable and set the Size of the variable according to your requirement. here in this code i have mentioned MAX.

Now Using

SELECT  @TempString =  @TempString + CityName +',' FROM Tbl_City


Statement we can append all the values in @TempString separated by comma.
@TempString will contain a extra comma at the end. so we need to remove that with the help of

SUBSTRING(@TempString,0,LEN(@TempString))


DECLARE @TempString VARCHAR(MAX)
SET @TempString = ''

SELECT @TempString = @TempString + CityName +',' FROM Tbl_City

SELECT SUBSTRING(@TempString,0,LEN(@TempString))

Comments or Responses

Posted by: Pandians on: 8/30/2009 Level:Silver | Status: [Member] [MVP]
Hi

Nice effort.

We have two more options...
1.COALESCE
2.XQuery

Cheers

Posted by: Lakhangarg on: 8/30/2009 Level:Silver | Status: [Member] [Moderator]
Hi Pandians-

Thanks for adding valuable information..

Login to post response