Разбить строку динамически - PullRequest
2 голосов
/ 26 апреля 2019

У меня есть таблица, как показано ниже:

Column1   Column2        Column3
-----------------------------------
A         NULL           NULL
A]B       NULL           NULL
A]B]C     NULL           NULL

Таких записей может быть несколько миллионов, и мне нужен SQL-запрос для получения вывода, как показано ниже

Column1  Column2    Column3
-----------------------------
A        NULL       NULL
A        B          NULL
A        B          C

Ответы [ 3 ]

1 голос
/ 26 апреля 2019

Вы можете попробовать ниже запрос:

    --test data
    declare @tbl table (Col1 varchar(10), Col2 varchar(10), Col3 varchar(10));
    insert into @tbl values
    ('a',null,null),
    ('a]b',null,null),
    ('a]b]c',null,null);


    select case when firstIdx = 0 then col1 else substring(col1, 1, firstIdx - 1) end Col1,
           case when firstIdx = 0 
             then null 
             else case when secondIdx = 0 
               then substring(col1, firstIdx + 1, 100)
               else substring(col1, firstIdx + 1, secondIdx - firstIdx - 1) 
             end
           end Col2,
           case when secondIdx = 0 
             then null
             else substring(col1, secondIdx + 1, 100) 
           end Col3
    from (
        select Col1,
              charindex(']', Col1) firstIdx,
              charindex(']', Col1, charindex(']', Col1) + 1) secondIdx
        from @tbl
    ) a
0 голосов
/ 26 апреля 2019

2 шага это процесс а) вам нужно создать функцию как:

CREATE FUNCTION [dbo].[split]
(
    @string varchar(MAX),
    @delimiter CHAR(1),
    @pos INT 
)
RETURNS varchar(255)
AS
BEGIN
    DECLARE @start INT, @end INT, @count INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string), @count = 1 
    WHILE @start < LEN(@string) + 1 BEGIN
        IF @end = 0 
            SET @end = LEN(@string) + 1 

        IF @count = @pos
            RETURN SUBSTRING(@string, @start, @end - @start)

        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)
        SET @count = @count + 1 

    END 
    RETURN '' -- not found
END

б) получить значение всех для всех 3 столбцов, как это

select isnull(dbo.split(cloumn1, ',', 0),'') as Column1,isnull(dbo.split(cloumn1, ',', 1),'') as Column2, isnull(dbo.split(cloumn1, ',', 2),'') as Column3 from <Table_Name>
0 голосов
/ 26 апреля 2019

Вы можете справиться с этим, используя несколько CTE, разделенных запятыми.

Ниже в запросе есть две таблицы CTE t0 и t1.Таблица t0 определяет положение первого ']', используя функцию charindex, и аналогично, t1 используется для определения положения следующего ']'.

Используя функцию case statement и substring, вы можете получить желаемый результат.

with t0 as ( select Column1, Column2 ,  Column3, charindex(']',Column1) pos from #tbl),
     t1 as (select  Column1, Column2 ,  Column3, charindex(']',Column1,t0.pos+1) pos from t0)
select case when t0.pos = 0 then t0.column1 else substring(t0.Column1,0, t0.pos )  end Column1,
       case when t0.pos = 0 then null else substring(t0.Column1,t0.pos+1,case when t1.pos= 0 then len(t0.Column1)+1 else len(t0.Column1)- t1.pos end)end Column2,
       case when (t0.pos = 0 or(t0.pos <>0 and t1.pos =0)) then null else substring(t0.Column1,t1.pos+1, len(t0.Column1)+1 )   end Column3 
from t0
inner join t1 on t0.Column1 = t1.Column1  

выход

Column1 Column2 Column3
------- ------- -------
A       NULL    NULL
A       B       NULL
A       B       C
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...