Monday, March 8, 2010

How to display table records as comma separated values in sql server 2005

IF OBJECT_ID(N'tempdb..#Employee') IS NOT NULL
DROP TABLE #Employee

IF OBJECT_ID(N'tempdb..#Dept') IS NOT NULL
DROP TABLE #Dept

CREATE TABLE #Employee (EmpID int, DeptID int, FName varchar(50), LName varchar(50))

CREATE TABLE #Dept(DeptID int,DeptName varchar(100))


INSERT INTO #Employee VALUES(1,1,'Vinay','Kumar')
INSERT INTO #Employee VALUES(2,1,'Piyush','Mundra')
INSERT INTO #Employee VALUES(3,2,'Srinivasan','Nagarajan')
INSERT INTO #Employee VALUES(4,2,'Bharat','Prasad')
INSERT INTO #Employee VALUES(5,3,'Varun','Rokkam')

INSERT INTO #Dept VALUES(1,'Finance')
INSERT INTO #Dept VALUES(2,'IT')
INSERT INTO #Dept VALUES(3,'Sales')

SELECT D.DeptName,
(SELECT FName + ',' FROM #Employee E WHERE E.DeptID = D.DeptId FOR XML PATH(''))
FROM #Dept D

No comments: