Wednesday, November 27, 2013

Split one long comma string into multi column new table

CREATE TABLE Table1
([Field1] varchar(38))
;

INSERT INTO Table1
([Field1])
VALUES
('Apples,oranges, pears, berries, melons')
;

WITH Split_Fields (Field, xmlfields)
AS
(
    SELECT Field1 AS Field,
    CONVERT(XML,'<Fields><field>'
    + REPLACE(Field1,',', '</field><field>') + '</field></Fields>') AS xmlfields
      FROM Table1
)

 SELECT Field,    
 xmlfields.value('/Fields[1]/field[1]','varchar(100)') AS Field1,  
 xmlfields.value('/Fields[1]/field[2]','varchar(100)') AS Field2,
 xmlfields.value('/Fields[1]/field[3]','varchar(100)') AS Field3,  
 xmlfields.value('/Fields[1]/field[4]','varchar(100)') AS Field4,
 xmlfields.value('/Fields[1]/field[5]','varchar(100)') AS Field5
 FROM Split_Fields

No comments:

Post a Comment