I have recently discovered Common Table Expressions (CTEs), thanks to the San Diego Tech Immersion Group. I found a CTE that I was able to modify to produce the table of tokens from a string, just like the function above. Here's my modified query with a test string:
DECLARE @str AS NVARCHAR(MAX)I've tested this extensively for almost 2 minutes!
DECLARE @separator AS NVARCHAR(2)
SET @str = 'test1
test2
test3
test4'
SET @separator = CHAR(13) + CHAR(10)
;
WITH Split_CTE(rowNum, stringStart, stringEnd) AS
(
SELECT
1 AS rowNum,
CAST(1 AS BIGINT) AS stringStart,
CHARINDEX(@separator, @str) AS stringEnd
UNION ALL
SELECT
rowNum + 1 AS rowNum,
stringEnd + LEN(@separator) AS stringStart,
CHARINDEX(@separator, @str, stringEnd + 1) AS stringEnd
FROM Split_CTE
WHERE stringEnd > 0
)
SELECT
rowNum,
SUBSTRING(@str, stringStart,
CASE WHEN stringEnd > 0 THEN stringEnd - stringStart ELSE 2000000000 END) AS StringValue
FROM Split_CTE
;
But seriously, if it fails when testing the application I'm working on now, I'll modify this post.