有时想根据某个标识截取一下字符串,此时如果能有一个像ASP.NET里面的Split方法,真是不错哦。
自己写一个SplitString函数吧,下面我的实现代码,供大家参考。
 
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE function [dbo].[SplitString]
    (
        @Input nvarchar(max),
        @Separator nvarchar(max)=',', 
        @RemoveEmptyEntries bit=1 
    )
    returns @TABLE table 
    (
        [Id] int identity(1,1),
        [Value] nvarchar(max)
    ) 
    as
    begin 
        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
        return
    end
函数、表都建好了,开始调用测试:
 
declare @str1 varchar(max), @str2 varchar(max), @str3 varchar(max)
set @str1 = '1,2,3'
set @str2 = '1###2###3'
set @str3 = '1###2###3###'
select [Value] from [dbo].[SplitString](@str1, ',', 1)
select [Value] from [dbo].[SplitString](@str2, '###', 1)
select [Value] from [dbo].[SplitString](@str3, '###', 0)
输出结果如下图所示:

里面还有个自增的[Id]字段哦,在某些情况下有可能会用上的,例如根据Id来保存排序等等。
例如根据某表的ID保存排序:
 
至些,sql server中实现split()函数的内容就介绍完了,希望对大家有所帮助。