33

我在 SQL Server 2008 上有一个 T1 表,它有一个 XML 列 EventXML。我想查询某个节点包含特定值的所有行。更好的是,我想检索不同节点中的值。表T1:

T1:
   EventID, int
   EventTime, datetime
   EventXML, XML

这是一个示例 XML 层次结构:

<Event>
   <Indicator>
      <Name>GDP</Name>
   </Indicator>
   <Announcement>
      <Value>2.0</Value>
      <Date>2012-01-01</Date>
   </Announcement>
</Event>
  1. 如何查找与“GDP”指标相关的所有行;
  2. 如何获取“GDP”指标的所有值;
4

2 回答 2

64

这个怎么样?

SELECT 
    EventID, EventTime,
    AnnouncementValue = t1.EventXML.value('(/Event/Announcement/Value)[1]', 'decimal(10,2)'),
    AnnouncementDate = t1.EventXML.value('(/Event/Announcement/Date)[1]', 'date')
FROM
    dbo.T1
WHERE
    t1.EventXML.exist('/Event/Indicator/Name[text() = "GDP"]') = 1

它将找到所有/Event/Indicator/Name等于的行,GDP然后它将显示这些行的<Announcement>/<Value><Announcement>/<Date>

请参阅SQLFiddle 演示

于 2012-11-02T13:21:21.500 回答
9
DECLARE @t XML = '
<Event>
   <Indicator>
      <Name>GDP</Name>
   </Indicator>
   <Announcement>
      <Value>2.0</Value>
      <Date>2012-01-01</Date>
   </Announcement>
</Event>
<Event>
   <Indicator>
      <Name>Other</Name>
   </Indicator>
   <Announcement>
      <Value>3.0</Value>
      <Date>2012-01-01</Date>
   </Announcement>
</Event>
'

SELECT  node.value('.', 'NUMERIC(20, 2)')
FROM    @t.nodes('/Event[Indicator/Name/node()=''GDP'']/Announcement/Value') t(node)
于 2012-11-02T13:22:45.177 回答