sql自定义函数实现字符串分割Split()功能

来源:互联网 发布:彩票大数据分析软件 编辑:程序博客网 时间:2024/04/30 07:03
SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE function [dbo].[SplitString](    @Input nvarchar(max),    @Separator nvarchar(max)=',',     @RemoveEmptyEntries bit=1 )returns @TABLE table (    [Id] int identity(1,1),    [Value] nvarchar(max)) asbegin     declare @Index int, @Entry nvarchar(max)    set @Index = charindex(@Separator,@Input)    while (@Index>0)    begin        set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1)))        if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')            begin                insert into @TABLE([Value]) Values(@Entry)            end        set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input))        set @Index = charindex(@Separator, @Input)    end    set @Entry=ltrim(rtrim(@Input))    if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')        begin            insert into @TABLE([Value]) Values(@Entry)        end    returnend

调用函数如下:
select [Value] from [dbo].[SplitString](‘胶原蛋白/胶原/胶原水解物/’, ‘/’, 1)
select [Value] from [dbo].[SplitString](‘胶原蛋白/胶原/胶原水解物/’, ‘/’, 0)

运行结果如下:
运行结果

里面还有个自增的[Id]字段,在某些情况下有可能会用上的,例如根据Id来保存排序等等。
例如根据某表的ID保存排序:
update a set a.[Order]=t.[Id] from [dbo].[表] as a join [dbo].SplitString(‘1,2,3’, ‘,’, 1) as t on a.[Id]=t.[Value]

0 0