从 sum 中删除一个 xml 节点,在 XPath 到 SQL Server XML 列中

2021-10-02 00:00:00 xml xpath sql-server

我有这个 XPath 表达式,它对最深的 XML 层次结构中的所有节点求和,而不使用节点名称:

I have this XPath expression, which sum all nodes in the deepest XML hierarchy, without using nodes names:

select  @data.value('sum(//*[not(*)])', 'float')

如何根据名称对一个节点进行例外处理?

How do I make an exception of one node, by its name?

说这是xml:

<c>
  <b1>
    <a>1</a>
    <d>4</d>
    <g>5</g>
 </b1>
 <b1>
   <a>7</a>
   <d>1</d>
   <g>2</g>
 </b1>
</c>

我希望总和包含d"和g",没有a",但a"将作为参数传递,因此需要在表达式中表示为参数.我尝试了以下方法:

I would like the sum to contain "d" and "g", without "a", but "a" will be pass as parameter and so need to be represented as parameter inside the expression. I've tried the following:

declare @except varchar(max) = 'a'


select  @data.value('sum(//*[not(*)])', 'float') - @data.value('sum(//*:local-name()=sql:variable("@except"))', 'float')

但没有成功.

推荐答案

虽然 Marc 的回答是我最会做的,但我有一个小技巧给你,下面

While Marc's answer is what i would do mostly, I have a small hack for you, below

select  @data.value('sum(//*[not(*)])', 'float')- @data.value('sum(//*:a)', 'float')

相关文章