sql server 函数

1.Fun_Split 分割字符串,形成返回表

CREATE FUNCTION [dbo].[Fun_Split]
(    
    @Items VARCHAR(MAX),
    @SplitStr VARCHAR(MAX)
)
RETURNS @SplitTable TABLE(Item VARCHAR(MAX)) 
AS
BEGIN
    DECLARE @Split_Index INT=0;
    DECLARE @Split_len INT=0;
    SET @Items = RTRIM(LTRIM(@Items));
    SET @Split_Index = CHARINDEX(@SplitStr,@Items);
    SET @Split_len=LEN(@SplitStr);
    WHILE(@Split_Index>=1)
    BEGIN    
        INSERT INTO @SplitTable VALUES(LEFT(@Items,@Split_Index-1));
        SET @Items = SUBSTRING(@Items,@Split_Index + @Split_len,LEN(@Items)-@Split_Index);
        SET @Split_Index = CHARINDEX(@SplitStr,@Items);
    END
    IF(@Items<>'')
        INSERT INTO @SplitTable VALUES(@Items);
    RETURN
END

2.Fun_arrlen 分割字符串,返回长度

CREATE FUNCTION [dbo].[Fun_arrlen]
(    
    @Str varchar(max),
    @SplitStr varchar(max)
)
RETURNS int 
AS
begin
     Declare @i Int  
     Set @i = (Len(@Str) - Len(Replace(@Str,@SplitStr,'')))/Len(@SplitStr) +1 
     Return(@i)
end

3.Fun_GetStrIndex 模拟数组获取值

CREATE FUNCTION [dbo].[Fun_GetStrIndex]
(    
    @Str varchar(max),
    @SplitStr varchar(max),
    @index int
)
RETURNS varchar(max) 
AS
begin 
    declare @location int
    declare @start int
    declare @next int
    declare @seed int

    set @str=ltrim(rtrim(@str))
    set @start=0
    set @next=0
    set @seed=len(@SplitStr)
 
    set @location=charindex(@SplitStr,@str)
    while @location<>0 and @index>@next
    begin
        set @start=@location+@seed
        set @location=charindex(@SplitStr,@str,@start)
        set @next=@next+1
    end
    if @location =0 select @location =len(@str)+1
    return substring(@str,@start,@location-@start);
end

运行结果:

posted @ 2016-01-26 14:56  点点_滴滴  阅读(215)  评论(0编辑  收藏  举报