Monday, December 03, 2012

Combine multiple rows into a comma separated Column in SQL-SERVER -2008

Posted by Rahul Kharde at 12:25 AM

If we required comma separated values form one to column in multiple rows.

Example
 

CREATE TABLE EMP
(
      EID       INT IDENTITY,
      ENAME   VARCHAR(100),
      DEPT    VARCHAR(100)
)

INSERT INTO EMP(ENAME,DEPT)
                  VALUES('ABC','SALE'),
                        ('PQR','IT'),
                        ('XYZ','HR'),
                        ('MNL','ADMIN')


DECLARE @DEPT VARCHAR(255)

SELECT @DEPT=COALESCE(@DEPT + ', ', '') + CAST(DEPT AS VARCHAR(100))
FROM EMP


SELECT @DEPT as 'Department'  


Output

Department
-----------------
SALE, IT, HR, ADMIN


If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

 

Popular Posts

Recent Comments

© 2011. All Rights Reserved | Help to understand .Net | Template by Blogger Widgets

Home | About | Top