I am trying to split a sentence with unlimited characters into multiples of 7 using a SQL UDF. Which means I am trying to break a sentence into rows with 7 characters in each rows. This is the approach that I felt was the quickest.
CREATE OR ALTER FUNCTION dbo.UDF_SplitStringIntoRows
(
@inputstring nvarchar(MAX)
)
RETURNS @OutputTbl TABLE
(
txt nvarchar(MAX),
seq INT IDENTITY
)
AS
BEGIN
IF(LEN(@inputstring) <= 40)
BEGIN
INSERT INTO @OutputTbl (txt)
SELECT SUBSTRING(@inputstring, 1,7) UNION
SELECT SUBSTRING(@inputstring, 8,7) UNION
SELECT SUBSTRING(@inputstring, 15,7) UNION
SELECT SUBSTRING(@inputstring, 23,7) UNION
SELECT SUBSTRING(@inputstring, 30,7) UNION
SELECT SUBSTRING(@inputstring, 37,7) UNION
SELECT SUBSTRING(@inputstring, 44,7)
END
RETURN
END
My query:
SELECT *
FROM dbo.UDF_SplitStringIntoRows('This is a demo function which') AS USSIR
WHERE USSIR.txt <> ''
Output:
Which is messing up the sequence of the sentence. Am I missing something here? Please suggest.