I have some xml like this
<variable>
<historicDates>
<item>
<date>2012/01/13</date>
<type>submitted</type>
</item>
<item>
<date>2012/01/12</date>
<type>required</type>
</item>
<item>
<date>2012/01/11</date>
<type>required</type>
</item>
</historicDates>
</variable>
I am trying to write a sql statement to get the maximum date where the type equals required. To compound the issue I the column is a nvarchar(max) so I know I have to cast it as xml even before I start.
I've tried to figure out the cross apply but cannot get it to work. Any help would be appreciated.
Assuming your XML is in a variable named @xml
:
SELECT MAX(t.ItemDate)
FROM (SELECT Tbl.Col.value('date[1]', 'datetime') AS ItemDate,
Tbl.Col.value('type[1]', 'varchar(20)') AS ItemType
FROM @xml.nodes('//variable/historicDates/item') Tbl(Col)) t
WHERE t.ItemType = 'required'
Since you indicated SQL Server 2008, you could also use a CTE here:
WITH cteXMLtoTable AS (
SELECT Tbl.Col.value('date[1]', 'datetime') as ItemDate,
Tbl.Col.value('type[1]', 'varchar(20)') as ItemType
FROM @xml.nodes('//variable/historicDates/item') Tbl(Col)
)
SELECT MAX(ItemDate)
FROM cteXMLtoTable
WHERE ItemType = 'required'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.