1. 程式人生 > >自定義分割字串函式

自定義分割字串函式

create function [dbo].[f_split]
(
    @c varchar(2000),--需要分割的字串(例如:1,2,3,4,5    我|和|你)
    @split varchar(2)--分隔符(例如 ,  |  $)
)
returns @t table(col varchar(200))--返回表
as
    begin
        while(charindex(@split,@c)<>0)
        begin
            insert @t(col) values (substring(@c,1,charindex(@split,@c)-1))
            set @c = stuff(@c,1,charindex(@split,@c),'')
        end
        insert @t(col) values (@c)
        return
    end

 函式效果:

 

 

create function [dbo].[f_split]
(
    @str varchar(2000),--需要分割的字串(例如:1,2,3,4,5    我|和|你)
    @spliter varchar(2)--分隔符(例如 ,  |  $)
)
returns @tb table(ch varchar(200))--返回表
as
    begin
        declare @num int,@pos int, @nextpos int
        set @num = 0
        set @pos = 1
        while(@pos <= LEN(@str))
            begin
            select @nextpos = CHARINDEX(@spliter, @str, @pos)
            if(@nextpos = 0 or @nextpos is null)
            select @nextpos = LEN(@str) + 1
            insert into @tb values(RTRIM(LTRIM(SUBSTRING(@str, @pos, @nextpos - @pos))))
            select @pos = @nextpos+1
            end
        return
    end

函式二效果: