我有这样的表
---table 1----------------------------------------------------------
string|
14, 123, A, 1000, 2017-09-10, h, 2, a
14, 789, C, 8000, 2017-11-02, m, 2, c
--------------------------------------------------------------------
我想将此表列拆分为8列,并将其插入table2,如下所示:
---table 2----------------------------------------------------------
col1 | col2 | col3 | col4 | col5 | col6 | col7 | col8
14 123 A 1000 2017-09-10 h 2 a
14 789 C 8000 2017-11-02 m 2 c
但我无法做到!
答案 0 :(得分:0)
你可以用它。它会对你有用。
CREATE TABLE [dbo].[table1](
[col1] [varchar](1000) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[table2](
[col1] [varchar](100) NULL,
[col2] [varchar](100) NULL,
[col3] [varchar](100) NULL,
[col4] [varchar](100) NULL,
[col5] [varchar](100) NULL,
[col6] [varchar](100) NULL,
[col7] [varchar](100) NULL,
[col8] [varchar](100) NULL
) ON [PRIMARY]
INSERT INTO table1(col1) VALUES('1,2,3,4,5,6,7,8')
INSERT INTO table1(col1) VALUES('10,20,30,40,50,60,70,80')
;WITH Split_Names (xmlcol)
AS
(
SELECT
CONVERT(XML,'<ColName><name>'
+ REPLACE(col1,',', '</name><name>') + '</name></ColName>') AS xmlcol
FROM table1
)
INSERT INTO table2(col1,col2,col3,col4,col5,col6,col7,col8)
SELECT
xmlcol.value('/ColName[1]/name[1]','varchar(100)') AS col1
,xmlcol.value('/ColName[1]/name[2]','varchar(100)') AS col2
,xmlcol.value('/ColName[1]/name[3]','varchar(100)') AS col3
,xmlcol.value('/ColName[1]/name[4]','varchar(100)') AS col4
,xmlcol.value('/ColName[1]/name[5]','varchar(100)') AS col5
,xmlcol.value('/ColName[1]/name[6]','varchar(100)') AS col6
,xmlcol.value('/ColName[1]/name[7]','varchar(100)') AS col7
,xmlcol.value('/ColName[1]/name[8]','varchar(100)') AS col8
FROM Split_Names