SQL根据兄弟节点属性值选择XML节点

时间:2013-01-24 00:38:15

标签: sql-server xml

<Findings>
   <Finding EcinRecordID="1042893">
      <Name>Goal Length of Stay for the ORG</Name>
      <Selected Value="0" DisplayValue="No"/>
   </Finding>
   <Finding EcinRecordID="1042894">
      <Name>Goal Length of Stay for the GRG</Name>
      <Selected Value="1" DisplayValue="Yes"/>
      <NoteText>3 days</NoteText>
   </Finding>
</Findings>

2个挑战:

  1. 选择Findings / Finding / Name的节点值,其中Findings / Finding / Selected Value =“1”
  2. 选择Findings / Finding / NoteText的节点值,其中Findings / Finding / Selected Value =“1”
  3. 将其放入存储过程。我使用查询,存在和值尝试了至少3打版本。我可以得到Selected Value ='1',但似乎无法在Select语句中分配相应的Name值。

    SELECT
       p.value('(Payments[1]/Payment[1]/PreAuthCertNumber)[1]', 'varchar(20)') AS PriorAuthNumber
       ,qa.value('(Name[1])','varchar(255)') AS Question
       ,qa.value('(Findings/Finding/Name)[1]','varchar(255)') AS Answer
        FROM #ValueExample
        CROSS APPLY XMLDocument.nodes('/OutboundDataFeed/Patient/PatientAdmission') as t(p)
        CROSS APPLY XMLDocument.nodes('/OutboundDataFeed/Patient/PatientAdmission/CMAssessments/CMAssessment/Sections/Section/Questions/Question') as u(qa)
    

    谢谢!

2 个答案:

答案 0 :(得分:6)

declare @XML xml

set @XML = '
<Findings>
   <Finding EcinRecordID="1042893">
      <Name>Goal Length of Stay for the ORG</Name>
      <Selected Value="0" DisplayValue="No"/>
   </Finding>
   <Finding EcinRecordID="1042894">
      <Name>Goal Length of Stay for the GRG</Name>
      <Selected Value="1" DisplayValue="Yes"/>
      <NoteText>3 days</NoteText>
   </Finding>
</Findings>'

select @XML.value('(/Findings/Finding[Selected/@Value = "1"]/Name/text())[1]', 'varchar(255)') as Name,
       @XML.value('(/Findings/Finding[Selected/@Value = "1"]/NoteText/text())[1]', 'varchar(255)') as NoteText

结果:

Name                                     NoteText
---------------------------------------- -------------------------
Goal Length of Stay for the GRG          3 days

答案 1 :(得分:2)

仅供参考,当我尝试在我正在使用的XML字段的查询中实现此解决方案时,我发现Mikael Eriksson上面的答案中提供的语法对我不起作用。结构是正确的,我仔细检查它是否格式正确,但我只是得到了我的结果的空值。

提供的语法(摘自Mikael Eriksson的回答)是:

select @XML.value('(/Findings/Finding[Selected/@Value = "1"]/Name/text())[1]', 'varchar(255)') as Name,
       @XML.value('(/Findings/Finding[Selected/@Value = "1"]/NoteText/text())[1]', 'varchar(255)') as NoteText

我发现实际上对我有用的是稍微修改它如下(显然,这不是我自己的代码片段,但出于一致性的目的):

select @XML.value('(/Findings/Finding/Selected[@Value = "1"]/Name/text())[1]', 'varchar(255)') as Name,
       @XML.value('(/Findings/Finding/Selected[@Value = "1"]/NoteText/text())[1]', 'varchar(255)') as NoteText

以为我会发布作为其他任何可能遇到同样经历的人的替补。