Reputation: 123
I am facing problems while retrieving data from XML.
with xmlnamespaces ('x-elements' as x)
select
tb.[Profile].value('(x:ppr/x:static/refId)[1]', 'varchar(22)') testCol
from table1 tb
The above code works perfectly fine. But, when I pass the XML path in a function it compiles correctly but doesn't return data upon calling but just the xml path (that is passed to it).
CREATE FUNCTION testFunc
(
@p varchar(22)
)
RETURNS nvarchar(max)
AS
BEGIN
DECLARE @Rs nvarchar(max);
with xmlnamespaces ('x-elements' as x)
select
@Rs = tb.[Profile].value('(sql:variable("@p_path"))[1]', 'nvarchar(max)')
from table1 tb
RETURN (@Rs)
END
The result I am getting is "x:ppr/x:sta" (which is a path not the value) whereas it should return a value like "aJxk9pGntc5V" Please suggest a solution!
Upvotes: 0
Views: 160
Reputation: 138980
The parameter to the value()
function has to be a string literal. You can not replace it with a variable/parameter that contains the XQuery you want to execute.
From value() Method (xml Data Type)
Syntax
value (XQuery, SQLType)
XQuery
Is the XQuery expression, a string literal, that retrieves data inside the XML instance.
Your attempt to use sql:variable("@p_path")
will insert the value of @p_path
as a string to the XQuery. It will not replace the entire XQuery expression. It will translate to something like value('("x:ppr/x:sta")', 'varchar(100)')
Upvotes: 1