sql的split()函数

ALTER  function [dbo].[StrToList_Test](@Str varchar(max), @fg NVARCHAR(200))
returns  @table table(
    value nvarchar(max)
)
as
begin

declare @tempStr nvarchar(max),@len INT = LEN(@fg);
--去除前后分割符
while substring(@Str,1,@len)=@fg
begin
    set @Str=substring(@Str,@len+1,len(@Str))
end
while RIGHT(@Str,@len)=@fg
begin
    set @Str=substring(@Str,1,len(@Str)-@len)
end

if(len(@Str)>0)
begin
    while(charindex(@fg,@Str)>0)
    begin
        set @tempStr=substring(@Str,1,charindex(@fg,@Str)-1)
        insert into @table(value) values(@tempStr)
        set @Str=substring(@Str,charindex(@fg,@Str)+@len,len(@Str))
    end
    insert into @table(value) values(@Str)  --没有分割符保存值
end
return
end

调用如:select * from [dbo].[StrToList_Test]('ab||cd||ef||ghi||jg','||')

posted on 2018-02-07 10:53  itjeff  阅读(785)  评论(0编辑  收藏  举报

导航