Question: Is there a way in SQL server to create a function to have the following string 'ABC,DEF,GHI' output the value 3.

And then is it possible to have a function that would allow you to specify what token of the string you want output.
So input would be the string and the token you want returned.
input: ('ABC,DEF,GHI', 2)
output: DEF

Answer: 
The first question

```
declare @token varchar(20)
set @token = 'ABC,DEF,GHI'

select len(@token) - len(replace(@token ,',','')) + 1

```
this is much shorter than the code you are writing:

A short explanation: By replacing the `,` with `</x><x>` we just have to add a `<x>`in front and a `</x>` at the end and - voila! - we've got XML.

XML is easy to index. You must use the XQuery-function `sql:variable()` to get the variable index into the XPath.

```
DECLARE @string VARCHAR(MAX)='ABC,DEF,GHI'; 
DECLARE @index INT=2;

WITH AsXML AS 
(
    SELECT CAST('<x>' + REPLACE(@string,',','</x><x>') + '</x>' AS XML) AS Splitted
)
SELECT Splitted.value('/x[sql:variable("@index")][1]','varchar(max)')
FROM AsXML 

```

EDIT: Here you find a fully working example with this approach as a function.

```
CREATE FUNCTION dbo.Tokenizer
(
     @string VARCHAR(MAX)
    ,@index INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
    DECLARE @RetVal VARCHAR(MAX);

    WITH AsXML AS 
    (
        SELECT CAST('<x>' + REPLACE(@string,',','</x><x>') + '</x>' AS XML) AS Splitted
    )
    SELECT @RetVal = Splitted.value('/x[sql:variable("@index")][1]','varchar(max)')
    FROM AsXML;

    RETURN @RetVal; 
END
GO

SELECT dbo.Tokenizer( 'ABC,DEF,GHI',2); --Returns "DEF"
GO

--Clean up
DROP FUNCTION dbo.Tokenizer; 

```