Search This Blog

August 30, 2011

How to generate comma seprated values from rows of data in Sql Server

/*Before converting to comma separated values*/
SELECT NAME
FROM SYS.databases
order by name

/*Declare a variable to store the comma separated value*/
DECLARE @NameString VARCHAR(MAX)
SELECT @NameString =''

/*Convert the Rows to Comma Separated values*/
SELECT @NameString = @NameString + ISNULL(NAME,'')+', '
FROM SYS.databases
order by name

/* Remove the comma at the end of the value*/
SELECT @NameString = LEFT(@NameString,LEN(@NameString)-1)

/*Display the Comma seprated values*/
SELECT @NameString AS Name



Second Method


/*Before converting to comma separated values*/
SELECT NAME
FROM SYS.databases
order by name

/*Declare a variable to store the comma separated value*/
DECLARE @NameString VARCHAR(MAX)

/*Convert the Rows to Comma Separated values using COALESCE function*/
SELECT @NameString = COALESCE(@NameString + ', ','') + Name
FROM SYS.databases
order by name

/*Display the Comma separated values*/
SELECT @NameString AS Name