Thursday, 19 June 2014

Concatenate Column Values of a table using COALESCE

DECLARE @ColumnNameList VARCHAR (MAX)
 SELECT   @ColumnNameList   = COALESCE (@ColumnNameList +',' , '') + Column Name
                                                             FROM
                                                               <<Table Name>>
SELECT @ColumnNameList


Eg:
Create table Emp(empid int, ename varchar(100))
Insert into Emp values(1,'Ganga');
Insert into Emp values(1,'Raju');
Insert into Emp values(1,'Kondapalli');


DECLARE @ColumnNameList VARCHAR (MAX)
 SELECT   @ColumnNameList   = COALESCE (@ColumnNameList +',' , '') + ename
                                                                                 FROM
                                                                                   Emp
SELECT @ColumnNameList


Result:

Ganga,Raju,Kondapalli

No comments:

Post a Comment