sql server 2008 r2 根据分节符拆分字符串(方法3)(速度最快)

--CREATE FUNCTION [dbo].[tf_split_char2]
ALTER FUNCTION [dbo].[tf_split_char2]
    (
      --根据分节符拆分字符串
      @cstring NVARCHAR(MAX) ,--输入字符串
      @csplit NVARCHAR(1)--分节符
    )
RETURNS @t TABLE
    (
      id INT IDENTITY(1, 1) ,
      cchar NVARCHAR(MAX)
    )
AS
    BEGIN
        DECLARE @ilocation INT= 0;
        DECLARE @inextlocation INT= 1;
        DECLARE @ilen INT; 
        WHILE @inextlocation > 0
            BEGIN
                SET @inextlocation = CHARINDEX(@csplit, @cstring,
                                               @ilocation + 1);
                SET @ilen = CASE WHEN @inextlocation > 0 THEN @inextlocation
                                 ELSE LEN(@cstring) + 1--最右边一节字符串
                            END - @ilocation - 1;--截取字符串的长度
                INSERT  INTO @t
                        ( cchar
                        )
                VALUES  ( SUBSTRING(@cstring, @ilocation + 1, @ilen)
                        );
                SET @ilocation = @inextlocation;
            END;
        RETURN;
    END;

  

原文地址:https://www.cnblogs.com/bgbird/p/9869517.html