从特定位置提取定界子字符串

时间:2020-06-16 21:01:00

标签: sql sql-server

我的数据集带有不规则的分隔符。每个值都由“-”和“ -1”定界。

enter image description here

如果我尝试在Excel中定界此数据集,则会得到:

enter image description here

但是我需要的是:

enter image description here

1 个答案:

答案 0 :(得分:0)

下面的功能是自定义的分隔符。

create function [fnSplitDelimiter] 
(
    @line nvarchar(max),
    @splitOn nvarchar(5) = ','

)
returns @rtnValue Table
(
    id int not null IDENTITY (1,1) primary key clustered, 
    data nvarchar(1000) not null
)
as 
begin 
    if @line is null return 

    declare @split_on_len int = len(@splitOn)
    declare @start_at int = 1
    declare @end_at int
    declare @data_len int 

    while 1=1 
    begin 
        set @end_at = CHARINDEX(@splitOn, @line, @start_at)
        set @data_len = case @end_at 
                        when 0 then LEN(@line) 
                        else @end_at - @start_at end 

        insert into @rtnValue (data) values (SUBSTRING(@Line,@start_at, @data_len));
        if @end_at = 0 break;
        set @start_at = @end_at + @split_on_len
    end
    Return 
End 

这是显示实现该功能以获得所需结果的示例。 enter image description here

declare @pk nvarchar (25) 
set @pk = '123-456-789-101-111--1'

select 
(select data from [fnSplitDelimiter] (REPLACE ((REPLACE(@pk, '-', '|')), '||', '|-'),'|') where id = 1 ) as [col a],
(select data from [fnSplitDelimiter] (REPLACE ((REPLACE(@pk, '-', '|')), '||', '|-'),'|') where id = 2 ) as [col b],
(select data from [fnSplitDelimiter] (REPLACE ((REPLACE(@pk, '-', '|')), '||', '|-'),'|') where id = 3 ) as [col c],
(select data from [fnSplitDelimiter] (REPLACE ((REPLACE(@pk, '-', '|')), '||', '|-'),'|') where id = 4 ) as [col d],
(select data from [fnSplitDelimiter] (REPLACE ((REPLACE(@pk, '-', '|')), '||', '|-'),'|') where id = 5 ) as [col e],
(select data from [fnSplitDelimiter] (REPLACE ((REPLACE(@pk, '-', '|')), '||', '|-'),'|') where id = 6 ) as [col f]

enter image description here