I am trying to write a scalar value function in SQL Server 2008 R2 that will take a chunk of XML and an XQuery path, and return the result as a string. Looking at just the T-SQL to perform the XML XQuery for the time being, the following example shows two statements (1 & 2). The first one should work apparently, but doesn't. The second is the same thing but without the use of sql:variable()
.
declare @xml xml
set @xml = '<?xml version="1.0" encoding="UTF-8"?>
<Response version="1.0">
<Transaction>
<Processing>
<Return>Some text that I need to extract.</Return>
</Processing>
</Transaction>
</Response>'
declare @xquery varchar(100)
set @xquery = '/Response/Transaction/Processing/Return'
-- Statement 1 : This should work, but it doesn't
select
CAST(@xml.query('data(*[local-name(.) = sql:variable("@xquery")])') as varchar(max))
-- Statement 2 : This does work
select
CAST(@xml.query('data(/Response/Transaction/Processing/Return)') as varchar(max))
Can anyone tell me why this is not working? What am I doing wrong, if indeed whether it is at all possible?
I have looked at numerous supposed working examples of this on this site, which is how I arrived at the above code, but I can't figure out why my implementation is not working.
This is not possible... sql:variable is meant to deliver a certain value, not a full path...
The only chance I know of is dynamic SQL:
(btw: To retrieve a value you should not use .query()
and cast it, better take .value()
declare @xml xml
set @xml = '<?xml version="1.0" encoding="UTF-8"?>
<Response version="1.0">
<Transaction>
<Processing>
<Return>Some text that I need to extract.</Return>
</Processing>
</Transaction>
</Response>';
-- Statement "direct value"
select @xml.value('(/Response/Transaction/Processing/Return)[1]','varchar(max)');
--dynamic SQL
declare @xquery varchar(100)='(/Response/Transaction/Processing/Return)[1]'
declare @dynamicSQL NVARCHAR(100)='select @xml.value(''' + @xquery + ''',''varchar(max)'')';
exec sp_executesql @dynamicSQL, N'@xml XML',@xml;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.