XQuery SQL从特定节点的子元素中提取文本值

时间:2017-11-09 15:23:21

标签: sql xml xquery xsql

我正在努力应对以下情况:我需要提取出来的' 10000'之后

...name="stateid"> <from>10000</from>

我设法从第一个节点audittrail中提取了一些我需要的东西

SELECT ref.value ('@datetime', 'nvarchar(364)') as [LastTimeActioned],
ref.value ('@changedby', 'nvarchar(364)') as [Actioned_By]
FROM Audit 
CROSS APPLY audit.Xml.nodes ('/audittrail') R(ref)


<audittrail id="137943" datetime="29-Feb-2016 15:42:06" changedby="quality" type="update">
   <fields>
     <field id="10022" name="Content Control">
      <mergedValue>dsad</mergedValue>
      <from />
      <to>dsad</to>
     </field>
     <field id="10027" name="Document Controller">
      <mergedValue>quality</mergedValue>
      <from />
      <to>quality</to>
    </field>
    <field id="10028" name="Document Owner">
      <mergedValue>quality</mergedValue>
      <from />
      <to>quality</to>
    </field>
    <field id="10029" name="Document Type">
      <mergedValue>Contract/Agreement</mergedValue>
      <from />
      <to>Contract/Agreement</to>
    </field>
    <field id="10067" name="StateId">
      <from>10000</from>
      <to>10000</to>
    </field>
    ....
  </fields>
</audittrail>

1 个答案:

答案 0 :(得分:1)

您正在寻找Xpath:

 (fields/field[@name="StateId"]/from)[1]

即。找到属性名称为值StateId的“fields / field”元素,并选择直接子from元素的内容:

SELECT 
   ref.value ('@datetime', 'nvarchar(364)') as [LastTimeActioned],
   ref.value ('@changedby', 'nvarchar(364)') as [Actioned_By],
   ref.value ('(fields/field[@name="StateId"]/from)[1]', 'integer') as StateIdFrom
FROM Audit 
CROSS APPLY audit.Xml.nodes ('/audittrail') R(ref)

SqlFiddle Here

请注意,您需要explicitly select the first text element导致XQuery(因此额外的括号()和[1])

技术上更正确,你也可以将选择限制在孩子text()的{​​{1}},即:

from