Wednesday, October 15, 2014

Single Row data are converted into Multiple Rows using Split function




For my project some of the column's data showing single row using comma separated like (Product Category – Bike, Car, Cloths, etc)
But, clients want to each product in each row, so I checked some blogs, then finally I got a solution. 

Testing purpose I used the below code

CREATE TABLE #temp (States varchar(15), City varchar(50))
INSERT INTO #temp VALUES ('Tamilnadu','Salem, Chenai, Trichy, Perambalur')
INSERT INTO #temp VALUES ('Karnataka','Bangalore, Mangalore, Mysore, Mandya, Haveri')

SELECT * FROM #temp

SELECT temp.States,
       Split.temp.value('.', 'VARCHAR(20)') AS City
FROM  ( SELECT States,
              CAST ('<M>' + REPLACE([City], ',', '</M><M>') + '</M>' AS XML) AS StringData
        FROM  #temp) AS temp
CROSS APPLY StringData.nodes ('/M') AS Split(temp);

DROP Table #temp