33

I have a table, T1, with a XML column, EventXML, on SQL Server 2008. I want to query all the rows where certain node contains a particular value. Better, I'd like to retrieve the value in a different node. The table T1:

T1:
   EventID, int
   EventTime, datetime
   EventXML, XML

Here is an example XML hierarchy:

<Event>
   <Indicator>
      <Name>GDP</Name>
   </Indicator>
   <Announcement>
      <Value>2.0</Value>
      <Date>2012-01-01</Date>
   </Announcement>
</Event>
  1. How to find all the rows related to "GDP" Indicator;
  2. How to get all values for "GDP" Indicator;
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 に答える