Get the Nth Token from a Delimited String
A scalar function that returns the Nth token from a delimited string using a recursive CTE.
Before STRING_SPLIT existed, extracting a specific token from a delimited string required cursors or messy nested CHARINDEX calls. This function uses a recursive CTE to walk the delimiters and return whichever token you ask for by ordinal position - 1-based.
Example: SELECT dbo.GetToken('one,two,three,four', ',', 3) -- returns three
CREATE FUNCTION dbo.[GetToken] (@String NVarChar(4000), @Delimiter NVarChar(4000), @Ordinal int)
RETURNS NVarChar(1000) AS
BEGIN
DECLARE @Result VarChar(4000);
WITH t(string, starts, pos, idx) as
(
SELECT @String, 1, charindex(@Delimiter, @String), 0
UNION ALL
SELECT
@String, pos + 1, charindex(@Delimiter, @String, pos + 1), idx + 1
FROM
t
WHERE
pos > 0
)
SELECT
@Result = substring(string, starts, case when pos > 0 then pos - starts else len(string) end)
FROM
t
WHERE
idx = @Ordinal;
RETURN @Result
END
GO