sql server 按固定字符截取第几个字符串

DROP FUNCTION Splic;
CREATE FUNCTION Splic
( @str nvarchar(200) ,
  @index int ,
  @char CHAR(1) = ',' )
RETURNS varchar(100)
AS
BEGIN
	SET @str='~'+REPLACE(@str,@char+'~'+@char,'*~*')+'~'

    IF @index > LEN(@str) - LEN(REPLACE(@str, @char, '')) + 1
    BEGIN
        RETURN '';
    END;

    DECLARE @i INT = 0 ,
        @curi INT ,
        @lasti INT= 0;

    WHILE ( @i < @index )
    BEGIN
        IF @lasti+1 > LEN(@str)
        BEGIN
            RETURN '';
        END;

        SELECT  @curi = @lasti + 1 ,
                @lasti = CHARINDEX(@char, @str, @curi) ,
                @i = @i + 1;

        IF @lasti = 0
        BEGIN
            SELECT  @lasti = LEN(@str)+1;
        END;
    END; 

    RETURN REPLACE( SUBSTRING(@str, @curi, @lasti-@curi),'~','');
END;
GO

  

posted @ 2022-04-22 17:03  瓜甜  阅读(336)  评论(0编辑  收藏  举报