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;