如何在sql中查询xml列

时间:2012-11-02 13:13:25

标签: xml sql-server-2008 tsql xquery

我有一个表,T1,在SQL Server 2008上有一个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”指标的所有值;

2 个答案:

答案 0 :(得分:62)

这个怎么样?

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 demo

答案 1 :(得分: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)