I have a need to create a function the will return nth element of a delimited string.
For a data migration project, I am converting JSON audit records stored in a S
Alternatively, one can use xml
, nodes()
and ROW_NUMBER
. We can order the elements based on their document order. For example:
DECLARE @Input VARCHAR(100) = '1a,2b,3c,4d,5e,6f,7g,8h'
,@Number TINYINT = 3
DECLARE @XML XML;
DECLARE @value VARCHAR(100);
SET @XML = CAST('' + REPLACE(@Input,',',' ') + ' ' AS XML);
WITH DataSource ([rowID], [rowValue]) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY T.c ASC)
,T.c.value('.', 'VARCHAR(100)')
FROM @XML.nodes('./x') T(c)
)
SELECT @value = [rowValue]
FROM DataSource
WHERE [rowID] = @Number;
SELECT @value;