2009-12-11 109 views
20

这是我的问题:从列中的以下XML中,我想知道名为“已启用”的变量的值是否等于'是'给定的步骤标识和一个组件Id。XPath来获取SQL XML值

'<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>' 

回答

31

更新

我recomendation将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) 

但是,如果必须使用获取的利益完全值的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) 

如果stepID和组件ID是列而不是变量,您应该在XPath过滤器中使用sql:column()而不是sql:variable。见Binding Relational Data Inside XML Data

而且finaly如果你需要的是检查所有脑干你可以使用exist() XML方法:

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

什么是@ x'? *(填充评论到15个字符)* – 2013-02-05 16:39:39

+3

我怀疑他有 'DECLARE @x XML =(xml from question);' 上面他的SQL Server查询窗口中的语句,以便使用该XML进行测试,但是将其从他的回答是因为它会是多余的。所有这一切说,我怀疑它是一个包含问题的XML的变量。 – sirdank 2014-02-25 14:53:39

2

我想你想的XPath查询是这样的:

/xml/box[@stepId="$stepId"]/components/component[@id="$componentId"]/variables/variable[@nom="Enabled" and @valeur="Yes"] 

这应该让你被命名为“已启用”与“是”的值指定的$ stepId和$ COMPONENTID变量。这假设你的xml以像你展示的标签开头,而不是

如果SQL Server 2005 XPath的东西非常简单(我从来没有使用它),那么上述查询应该可以工作。否则,其他人可能需要帮助你。

+0

谢谢,这有帮助。如果找到了匹配,我该如何返回true或false?或者返回0或1. – joerage 2009-12-11 22:04:48

+0

我不确定。您可以尝试如下所示: IF count(<您的xpath查询>)> = 1 SELECT 1 ELSE SELECT 0 – 2009-12-14 00:52:19

+0

您可以使用EXIST方法。 Field.EXIST( '的xpath') – 2013-09-23 14:48:54