0

我对 SQL 很陌生,请原谅任何无知。我有一个名为“temp”的表,其中包含一个带有一个长逗号分隔字符串的字段,因此:

Field1
Apples,oranges, pears, berries, melons

我想将以上内容插入到现有表中,即具有预定义列的“详细信息”,因此它看起来像这样:

Field1   Field2   Field3  Field4   Field5
Apples   Oranges  Pears   Berries  Melons 

我一直在阅读论坛,我认为我需要使用一个功能 - 但是我该怎么做呢?哪个功能最好?有人说 XML 函数最好?

问候,

迈克尔

4

3 回答 3

1

尝试这个

;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 演示

或者

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

插入另一个表(例如:详细信息),请尝试以下操作

;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
于 2013-06-11T09:46:44.683 回答
0

甲骨文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
于 2013-06-11T10:08:23.697 回答
0

通常 sql 用于结构化数据,逗号分隔的字符串将来自外部数据文件。如果您有可用的外部数据文件,请像这样加载数据。或者,如果必须,考虑将原始临时表导出到数据文件。

bulk insert tbl_fruits from file.csv with fieldterminator=','
于 2013-06-12T04:50:51.400 回答