String split with Transact-SQL

In spite of The STRING_SPLIT function is now available under compatibility level 130, knowing how to implement this function is something that is definitely worthwhile.
CREATE FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1
       
        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)
        
    END 
    RETURN 
END
GO
How to use:
DECLARE
    @_txt_tmp  NVARCHAR(MAX),
    @full_string NVARCHAR(MAX) = "Hello World From Transact-SQL"
DECLARE
    @cursor_for_spliting CURSOR
    SET @cursor_for_spliting = CURSOR FOR SELECT splitdata FROM [dbo].[fnSplitString](@full_string,'')
    OPEN @cursor_for_spliting FETCH NEXT FROM @cursor_for_spliting INTO @_txt_tmp
    WHILE @@FETCH_STATUS = 0
    BEGIN
        -- Do whatever with @_txt_tmp
    FETCH NEXT FROM @cursor_for_spliting INTO @_txt_tmp
END;
CLOSE @cursor_for_spliting ;
DEALLOCATE @cursor_for_spliting;

Comentarios