Sunday, 21 July 2013

Convert comma separated (csv) column values to rows - sql server

There are many ways to convert comma separated values to rows one option is to use functions. I will show you the other way of doing this. Let me show with an example.

Department table having multiple employees

DNo Employees
10 John,Mike,Bob
20 Mona,Lisa,Katie,David















Query Script

CREATE TABLE #Department
([Dno] INT, [Employees] varchar(MAX))

INSERT INTO #Department
([Dno], [Employees])
VALUES
(10, 'John,Mike,Bob'),
(20, 'Mona,Lisa,Katie,David')

SELECT D.DNo,
Dept.emp.value('.', 'VARCHAR(100)') AS Employee
FROM 
(
SELECT DNo, 
CAST('<emp>' + REPLACE(Employees, ',', '</emp><emp>') 
+ '</emp>' AS XML) AS Employee
FROM #Department
) AS D CROSS APPLY Employee.nodes('/emp') AS Dept(emp)


DROP TABLE #Department


This post covers similar questions in sql server

Split comma separated values (CSV) into multiple rows
Parsing CSV to rows sql server