用于获取SQL XML值的XPath

joe*_*age 23 t-sql sql-server xpath

这是我的问题:根据列中的以下XML,我想知道给定步骤Id和组件ID,名称为"Enabled"的变量的值是否等于"是".

'<xml>
  <box stepId="1">
    <components>
      <component id="2">
        <variables>
          <variable id="3" nom="Server" valeur="DEV1" />
          <variable id="4" nom="Enabled" valeur="Yes" />
        </variables>
      </component>
      <component id="3">
        <variables>
          <variable id="3" nom="Server" valeur="DEV1" />
          <variable id="4" nom="Enabled" valeur="No" />
        </variables>
      </component>
    </components>
  </box>
  <box stepId="2">
    <components>
      <component id="2">
        <variables>
          <variable id="3" nom="Server" valeur="DEV2" />
          <variable id="4" nom="Enabled" valeur="Yes" />
        </variables>
      </component>
      <component id="3">
        <variables>
          <variable id="3" nom="Server" valeur="DEV2" />
          <variable id="4" nom="Enabled" valeur="No" />
        </variables>
      </component>
    </components>
  </box>
</xml>'
Run Code Online (Sandbox Code Playgroud)

Rem*_*anu 36

更新

我的推荐是将XML分解为关系,并以面向集合的方式对结果关系进行搜索和连接,而不是在XML中搜索特定节点的过程方式.这是一个简单的XML查询,它可以删除感兴趣的节点和属性:

select x.value(N'../../../../@stepId', N'int') as StepID
  , x.value(N'../../@id', N'int') as ComponentID
  , x.value(N'@nom',N'nvarchar(100)') as Nom
  , x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box/components/component/variables/variable') t(x)
Run Code Online (Sandbox Code Playgroud)

但是,如果必须使用能够准确检索感兴趣值的XPath:

select x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
       variables/variable[@nom="Enabled"]') t(x)
Run Code Online (Sandbox Code Playgroud)

如果stepID和组件ID是列而不是变量,则应在XPath过滤器中使用sql:column()而不是sql:variable.请参阅绑定XML数据内部的关系数据.

最后,如果你只需要检查是否存在,你可以使用exists () XML方法:

select @x.exist(
  N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
      variables/variable[@nom="Enabled" and @valeur="Yes"]') 
Run Code Online (Sandbox Code Playgroud)

  • 什么是`@ x`?*(填充注释为15个字符)* (4认同)
  • 我怀疑他有'DECLARE @x XML =(来自问题的xml);`在SQL Server查询窗口中的语句之上,以便使用该XML进行测试但是将其从答案中删除,因为它本身就是多余的.所有这一切,我怀疑它是一个包含问题中的XML的变量. (3认同)