我想将excel(数据)文本“复制”到columns函数。 基本上我有一个字符串列,我想根据特定的分隔符将其拆分为多个列。
declare @t table (
id int,
name varchar(50)
)
insert into @t values (1,'abcd.ef.g')
insert into @t values (2,'ab.cdef.ghi')
insert into @t values (3,'a..d')
insert into @t values (4,'a')
select * from @t
id name
----------- --------------------------------------------------
1 abcd.ef.g
2 ab.cdef.ghi
3 a..d
4 a
--I would like to get result
id name1 name2 name3
----------- --------------------------------------------------
1 abcd ef g
2 ab cdef ghi
3 a (NULL) d
4 a (NULL) (NULL)
感谢
答案 0 :(得分:1)
declare @t table (id int,name varchar(50))
insert into @t values (1,'abcd.ef.g')
insert into @t values (2,'ab.cdef.ghi')
insert into @t values (3,'a..d')
insert into @t values (4,'a');
WITH Split_Fields (ID, xmlfields)
AS
(
SELECT ID ,
CONVERT(XML,'<Fields><field>'
+ REPLACE(name,'.', '</field><field>') + '</field></Fields>') AS xmlfields
FROM @t
)
SELECT ID
,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
╔════╦════════╦════════╦════════╦════════╦════════╗
║ ID ║ Field1 ║ Field2 ║ Field3 ║ Field4 ║ Field5 ║
╠════╬════════╬════════╬════════╬════════╬════════╣
║ 1 ║ abcd ║ ef ║ g ║ NULL ║ NULL ║
║ 2 ║ ab ║ cdef ║ ghi ║ NULL ║ NULL ║
║ 3 ║ a ║ ║ d ║ NULL ║ NULL ║
║ 4 ║ a ║ NULL ║ NULL ║ NULL ║ NULL ║
╚════╩════════╩════════╩════════╩════════╩════════╝