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]
1条答案
按热度按时间6kkfgxo01#
下面的函数是一个自定义分隔符拆分器。
这是一个显示如何实现函数以获得所需结果的示例。