I am newish to SQL to please excuse any ignorance. I have a table, called \'temp\' that contains one Field with one long comma seperated string, thus:
Field1
Ap
Try this
;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
SQLFiddle Demo
OR
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
(
SELECT
Field1 AS Field
,CONVERT(XML,'<Fields><field>' + REPLACE(Field1,',', '</field><field>') + '</field></Fields>') AS xmlfields
FROM Table1
) Split_Fields
To insert into another table (ex: Detail) try below
;WITH Split_Fields (Field, xmlfields)
AS
(
SELECT
Field1 AS Field
,CONVERT(XML,'<Fields><field>' + REPLACE(Field1,',', '</field><field>') + '</field></Fields>') AS xmlfields
FROM Table1
)
INSERT INTO Detail
SELECT
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
Oracle SQL:
SELECT REPLACE(SUBSTR(r_str, 1, INSTR(r_str, ',', 1, 1) - 1), ' ') AS r_substr_1
, REPLACE(SUBSTR(r_str, INSTR(r_str, ',', 1, 1) + 1, INSTR(r_str, ',', 1, 2) - INSTR(r_str, ',', 1, 1) - 1), ' ') AS r_substr_2
, REPLACE(SUBSTR(r_str, INSTR(r_str, ',', 1, 2) + 1, INSTR(r_str, ',', 1, 3) - INSTR(r_str, ',', 1, 2) - 1), ' ') AS r_substr_3
, REPLACE(SUBSTR(r_str, INSTR(r_str, ',', 1, 3) + 1, INSTR(r_str, ',', 1, 4) - INSTR(r_str, ',', 1, 3) - 1), ' ') AS r_substr_4
, REPLACE(SUBSTR(r_str, INSTR(r_str, ',', 1, 4) + 1), ' ') AS r_substr_5
FROM
(
SELECT 'Apples, oranges, pears,berries, melons' r_str FROM DUAL
);
Result: Apples oranges pears berries melons
Usually sql is used for structured data, and a comma separated string would come from an outside data file. If you have the outside data file available, load the data like this. Or consider exporting your original temp table to a data file if you have to.
bulk insert tbl_fruits from file.csv with fieldterminator=','