我有一个表,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>
答案 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>
。
答案 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)