在XQuery中比较子节点和元素

时间:2015-04-16 19:42:04

标签: sql sql-server xquery sqlxml xquery-sql

我试图查看sql中的xml文档是否满足某些要求。

CREATE TABLE #ValueExample
(
XMLDocument xml
)

INSERT INTO #ValueExample
VALUES ('<History>
  <step start="2/22/2015 5:17:55 PM" end="" user="Intake Processor">
    <type id="1" value="2" />
    <type id="2" value="0" />
    <type id="3" value="0" />
    <type id="4" value="0" />
  </step>
  <step start="2015-03-13 10:56:29.980" end="" user="BD Save Followup">
    <type id="0" value="5" />
    <type id="1" value="4" />
    <type id="2" value="3" />
    <type id="3" value="0" />
    <type id="4" value="0" />
  </step>
  <step start="2015-02-22 20:08:58.053" end="" user="BD Save Followup">
    <type id="0" value="5" />
    <type id="1" value="4" />
    <type id="2" value="174" />
    <type id="3" value="181" />
    <type id="4" value="0" />
  </step>
</History>')

我需要知道这个文档是否有一个具有的步骤节点  属性值为id = 2且value = 174的类型的子元素,  也是一个类型元素,其属性类型为id = 3和value = 181。

基本上,最后一个节点符合我的条件。这是我尝试过的sql,以及创建测试的方法。

我正在尝试的SQL

SELECT c.query('.') AS XMLFragment
,c.value('(@id)[1]','int') AS value
,c.query('..') as wholexml
,c.value('(@id)[1]','int') as id
,c.value('(@value)[1]','int') as value
,c.query('(//step/type)[1]') as typeelements
FROM #ValueExample
CROSS APPLY XMLDocument.nodes('//step/type') as t(c)

问题是我需要最后一个类型元素,按步骤分组......

我希望这很清楚,可以理解。如果您需要额外的澄清,请询问。

1 个答案:

答案 0 :(得分:0)

您可以使用sqlxml exist()方法

select
    t.c.query('.') AS XMLFragment
from #ValueExample as v
    cross apply v.XMLDocument.nodes('//step') as t(c)
where
    t.c.exist('type[@id=2 and @value=174]') = 1 and
    t.c.exist('type[@id=3 and @value=181]') = 1

<强> sql fiddle demo