根据子元素的最大值选择 SQL Server 中的 XML 节点 [英] Choose a XML node in SQL Server based on max value of a child element
问题描述
我试图根据位于子节点中的最大数据从 SQL Server 2005 XML 数据类型中选择一些值.
I am trying to select from SQL Server 2005 XML datatype some values based on the max data that is located in a child node.
我在 SQL Server 的一个字段中存储了多行 XML,类似于以下内容:
I have multiple rows with XML similar to the following stored in a field in SQL Server:
<user>
<name>Joe</name>
<token>
<id>ABC123</id>
<endDate>2013-06-16 18:48:50.111</endDate>
</token>
<token>
<id>XYX456</id>
<endDate>2014-01-01 18:48:50.111</endDate>
</token>
</user>
我想从这个 XML 列中执行一个选择,它确定令牌元素内的最大日期,并为每条记录返回类似于以下结果的数据行:
I want to perform a select from this XML column where it determines the max date within the token element and would return the datarows similar to the result below for each record:
乔 XYZ456 2014-01-0118:48:50.111
Joe XYZ456 2014-01-01 18:48:50.111
我试图为 xpath 找到一个 max 函数,它可以让我选择正确的标记元素,但我找不到一个可以工作的.
I have tried to find a max function for xpath that would all me to select the correct token element but I couldn't find one that would work.
我也尝试使用 SQL MAX 函数,但我也无法使用该方法使其正常工作.
I also tried to use the SQL MAX function but I wasn't able to get it working with that method either.
如果我只有一个令牌,它当然可以正常工作,但是当我有多个令牌时,我得到一个 NULL,很可能是因为查询不知道要提取哪个日期.我希望有一种方法可以在令牌元素上指定 where 子句 [max(endDate)]
但还没有找到方法来做到这一点.
If I only have a single token it of course works fine but when I have more than one I get a NULL, most likely because the query doesn't know which date to pull. I was hoping there would be a way to specify a where clause [max(endDate)]
on the token element but haven't found a way to do that.
这是一个当我只有一个令牌时有效的例子:
Here is an example of the one that works when I only have a single token:
SELECT
XMLCOL.query('user/name').value('.','NVARCHAR(20)') as name
XMLCOL.query('user/token/id').value('.','NVARCHAR(20)') as id
XMLCOL.query('user/token/endDate').value(,'xs:datetime(.)','DATETIME') as endDate
FROM MYTABLE
推荐答案
这个怎么样:
SELECT
TOP 1
XMLCOL.value('(/user/name)[1]', 'nvarchar(20)') as 'UserName',
Usr.Token.value('(id)[1]', 'nvarchar(20)') AS 'ID',
Usr.Token.value('(endDate)[1]', 'DateTime') as 'EndDate'
FROM
dbo.MyTable
CROSS APPLY
xmlcol.nodes('/user/token') AS Usr(Token)
ORDER BY
Usr.Token.value('(endDate)[1]', 'DateTime') DESC
您基本上是直接从 XML 中获取用户名"等原子"部分,然后交叉应用/user/token 列表并提取您想要的各个位 - 您会得到一个包含三列(用户名、ID、EndDate),您可以对它们进行排序和过滤.
You basically take the "atomic" part like 'UserName' directly from the XML, and then cross apply a list of /user/token and extract the individual bits you want - you get a result set of three columns (UserName, ID, EndDate) and you can order and filter those.
旁注:而不是这个:
XMLCOL.query('user/name').value('.','NVARCHAR(20)')
为什么不使用它 - 感觉容易多了!
why don't you use this - feels much easier!
XMLCOL.value('(/user/name)[1]', 'NVARCHAR(20)')
这篇关于根据子元素的最大值选择 SQL Server 中的 XML 节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!