You cannot use a variable as an XPath . The documentation on this subject is strict:
Syntax: nodes (XQuery) as Table (Column)
Arguments:
XQuery String Literal ...
Attempting to do this causes an error Msg 8172 :
The XML nodes must be a string literal.
But you can use variables inside XPath .
For example, instead of
declare @xml xml = '<nodes><a id="1"/><b id="2"/></nodes>'; declare @path varchar(100); set @path = '/nodes/b'; select xcvalue('@id', 'int') as id from @xml.nodes(@path) x(c); set @path = '/nodes/a'; select xcvalue('@id', 'int') as id from @xml.nodes(@path) x(c);
can be used
declare @xml xml = '<nodes><a id="1"/><b id="2"/></nodes>'; declare @nodeName varchar(20); set @nodeName = 'a'; select xcvalue('@id', 'int') as id from @xml.nodes('/nodes[1]/*[local-name()=sql:variable("@nodeName")]') x(c); set @nodeName = 'b'; select xcvalue('@id', 'int') as id from @xml.nodes('/nodes[1]/*[local-name()=sql:variable("@nodeName")]') x(c);