SQL分割字符串2

create function [dbo].[SplitString]

(
    @Input nvarchar(max),
    @Separator nvarchar(max)=',',
    @RemoveEmptyEntries bit=1 ,
    @position int
)
returns @TABLE table
(
    [Id] int identity(1,1),
    [Value] nvarchar(max)
)
as
begin
    declare @Index int, @Entry nvarchar(max)
    set @Index = charindex(@Separator,@Input)
    set @Input = @Input + @Separator
    
    declare @count int
    set @count = 1
    while (@Index>0)
    begin
        set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1)))
        
        if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
            begin
              if @count = @position
                begin
                   insert into @TABLE([Value]) Values(@Entry)
                end
            end

        set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input))
        set @Index = charindex(@Separator, @Input)
        set @count =  @count + 1;
    end
   
    return
end

------------------------------

     select  [Value] from [dbo].[SplitString2]('2012-12-25', '-', 1,1)
     select  [Value] from [dbo].[SplitString2]('2012-12-25', '-', 1,2)
     select  [Value] from [dbo].[SplitString2]('2012-12-25', '-', 1,3) 

 

 

posted @ 2012-06-13 09:58  宁静.致远  阅读(125)  评论(0编辑  收藏  举报