Is there a simple way to use a relative path within XQuery arithmetic within SQL Server?
e.g. with the below code, I'm repeating /a/b/
on both sides of the operator:
declare @x xml = '<a><b><x>10</x><y>20</y></b></a>'
select @x.value('((/a/b/x/text())[1] + (/a/b/y/text())[1])[1]','bigint')
More Info
NB: I'm aware that in the example above I could use the SUM function... Sadly that would not apply to my real use case, where I have multiple elements with various operations to be performed between them.
I'm also familiar with the nodes
option to do something like below:
select ab.b.value('((./x)[1] + (./y)[1])[1]','bigint')
from @x.nodes('/a/b') ab(b)
I'm also familiar with using outer apply
/cross apply
to access such subqueries when the XML is coming from a column rather than a variable. That's currently the route I'm taking, but it feels a little clunky.
I'm visualising a solution similar to this:
select @x.value('(/a/b[(./x)[1] + (./y)[1]])[1]','bigint')
; i.e. similar to how a filter can be applied to multiple elements within the context of the current path; but haven't found how that would be written (assuming this is even possible).