从特定位置提取分隔的子字符串

0wi1tuuw  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(259)

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

如果我尝试在excel中分隔此数据集,我会得到:

但我需要的是:

6kkfgxo0

6kkfgxo01#

下面的函数是一个自定义分隔符拆分器。

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

这是一个显示如何实现函数以获得所需结果的示例。

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]

相关问题