Convert Comma Separated column value to rows

mhn picture mhn · Dec 14, 2012 · Viewed 79.1k times · Source

I have a table Sample with data stored like below

Id   | String
--------------
1     abc,def,ghi
2     jkl,mno,pqr

I need the output like..

Id   | processedrows
--------------
1     abc
1     def
1     ghi
2     jkl
2     mno
2     pqr

How can I do the same with a select query in SQL Server?

Answer

SRIRAM picture SRIRAM · Dec 14, 2012

try this

 SELECT A.[id],  
     Split.a.value('.', 'VARCHAR(100)') AS String  
 FROM  (SELECT [id],  
         CAST ('<M>' + REPLACE([string], ',', '</M><M>') + '</M>' AS XML) AS String  
     FROM  TableA) AS A CROSS APPLY String.nodes ('/M') AS Split(a); 

refer here

http://www.sqljason.com/2010/05/converting-single-comma-separated-row.html