在SQL Server中拆分字符串

时间:2017-12-05 09:34:40

标签: sql sql-server

你能帮我完成这项任务吗?我有一个包含两列(ID,String)的表。该列中的字符串由'#'分隔。我需要制作专栏" Cut" enter image description here

2 个答案:

答案 0 :(得分:2)

这应该是诀窍。在行中拆分字符串,然后选择不同的值。如果您还需要String列,只需在id上加入您的表格。

declare @tbl as table (
    id int
    ,string varchar(25)
)

insert into @tbl values (1, 'A#B#C')
insert into @tbl values (1, 'A#B#C')
insert into @tbl values (1, 'A#B#C')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (3, 'G')



SELECT DISTINCT [Id], Split.a.value('.', 'VARCHAR(5)') AS [Cut]  
FROM (
    SELECT [Id], CAST('<M>' + REPLACE([String], '#', '</M><M>') + '</M>' AS XML) AS [String]
    FROM  @tbl
) AS A CROSS APPLY [String].nodes ('/M') AS Split(a);

答案 1 :(得分:1)

这是另一种方式:

CREATE TABLE MyStrings (
    ID INT,
    String VARCHAR (25)
    );
INSERT INTO MyStrings VALUES
(1, 'A#B#C'),
(1, 'A#B#C'),
(1, 'A#B#C'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(2, 'K#L#X#W#I'),
(3, 'G');

WITH CTE AS(
SELECT *,
        ROW_NUMBER () OVER (PARTITION BY ID ORDER BY ID) AS RN
FROM MyStrings
    )
    SELECT ID, String,
            SUBSTRING(String, IIF(RN = 1 , RN, RN + (RN-1)) 
                      , 1) AS Cut
    FROM CTE;

OR

WITH CTE AS(
SELECT *,
        REPLACE (String, '#', '') AS STR,
        ROW_NUMBER () OVER (PARTITION BY ID ORDER BY ID) AS RN
FROM MyStrings
    )
    SELECT ID, String, SUBSTRING(STR, RN, 1) AS Cut
    FROM CTE;

结果:

+----+-----------+-----+
| ID |  String   | Cut |
+----+-----------+-----+
|  1 | A#B#C     | A   |
|  1 | A#B#C     | B   |
|  1 | A#B#C     | C   |
|  2 | K#L#X#W#I | K   |
|  2 | K#L#X#W#I | L   |
|  2 | K#L#X#W#I | X   |
|  2 | K#L#X#W#I | W   |
|  2 | K#L#X#W#I | I   |
|  3 | G         | G   |
+----+-----------+-----+