我在SQL server表的一列中有一个XML数据。XML数据看起来像:
<MainTag dateCreated="2/6/2020 9:22:48 AM">
</MainTag>
我正在编写一个查询,以从具有最新创建日期的XML中获取数据。我尝试使用order by子句,但由于日期存储为字符串,所以提取了错误的XML。
我尝试过的查询:
SELECT TOP 1 tbl.Id,
c.value(''@dateCreated'',''VARCHAR(max)'') AS [dateCreated]
FROM tbl
CROSS APPLY tbl.Column.nodes(''/MainTag[1]'') AS t(c)
order by c.value(''@dateCreated'', ''VARCHAR(max)'') DESC;
如果两个XML类似:
<MainTag dateCreated="2/6/2020 9:22:48 AM"> and <MainTag dateCreated="5/3/2016 8:12:37 AM">
那么提取的Xml就是
<MainTag dateCreated="5/3/2016 8:12:37 AM">
但是我想要
<MainTag dateCreated="2/6/2020 9:22:48 AM">
要提取。
不知道该怎么做。
尝试将最后一行替换为:
order by convert(datetime, c.value('@dateCreated', 'VARCHAR(max)'), 103) desc;