I just wanted to play a little bit with the DelimitedSplit8k and this is what came out.
CREATE FUNCTION [dbo].[ItemsLength]
(
@pString [varchar](8000),
@pDelimiter [char](1)
)
RETURNS TABLE WITH SCHEMABINDING
AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover NVARCHAR(4000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(@pString),0) + 1) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteDelims(N, row) AS (--==== This returns position of each delimiter
SELECT 0 , 1 UNION ALL
SELECT t.N, ROW_NUMBER() OVER(ORDER BY t.N) + 1 FROM cteTally t WHERE SUBSTRING(@pString + ' ',t.N,1) = @pDelimiter
)
SELECT d2.N - d1.N - 1
FROM cteDelims d1
JOIN cteDelims d2 ON d1.row = d2.row - 1
;