I'm trying to make the top solution's topmost code from here into a SQL user-defined function. However, when I try to use a variable for the number 4 (in the first argument of the value function), it barfs.
So this works:
SELECT CAST('<x>' + REPLACE(@Input,',','</x><x>') + '</x>' AS XML).value('/x[4]','int')
...but whenever I try to replace the '/x[4]' to use a variable in place of the 4, I get a message like
The argument 1 of the XML data type method "value" must be a string literal.
Here is my full user-defined function so far... just learning how:
USE [DBName]
GO
CREATE FUNCTION fx_SegmentN
(@Input AS VARCHAR(100),
@Number AS VARCHAR(1))
RETURNS varchar(100)
AS
BEGIN
DECLARE @ValueStringLiteral varchar(14)
SET @ValueStringLiteral = '/x[' + @Number + ']'
RETURN '' +
CASE
WHEN @Number <1
THEN ('ERROR')
WHEN @Number = 1
THEN (LEFT(@Input, CHARINDEX('-', @Input, 1)-1))
WHEN @Number > 1
--THEN (SELECT CAST('<x>' + REPLACE(@Input,',','</x><x>') + '</x>' AS XML).value('/x[4]','int')) --THIS LINE WORKS
THEN (SELECT CAST('<x>' + REPLACE(@Input,',','</x><x>') + '</x>' AS XML).value('/x[' + @Number + ']','int')) --THIS ONE DOES NOT
ELSE
(NULL)
END + ''
END