gpt4 book ai didi

sql-server - `nodes()` 方法是否保持文档顺序?

转载 作者:数据小太阳 更新时间:2023-10-29 01:40:31 26 4
gpt4 key购买 nike

xml 数据类型的 nodes() 方法是否按文档顺序返回节点?

例如,如果有这样的数据:

declare @xml xml;
set @xml = '<Fruits><Apple /><Banana /><Orange /><Pear /></Fruits>';

查询为

select T.c.query('.')
from @xml.nodes('/Fruits/*') T(c);

元素会按文档顺序返回吗?如果省略 order by 子句,则已知 select 返回的行顺序是未定义的。 select ... from ... .nodes() 是这种情况,还是异常(exception)?

最佳答案

是的,nodes() 按文档顺序生成行集。查询计划中用于执行此操作的运算符是 Table Valued Function XML Reader .

Table-valued Function XML Reader inputs an XML BLOB as a parameter and produces a row set representing XML nodes in XML document order. Other input parameters may restrict XML nodes returned to a subset of XML document.

但是没有 order by 的查询有一个未定义的顺序,所以没有保证。

解决此问题的一种方法是使用 row_number() over() 子句中的表值函数生成的 id 并按顺序使用生成的数字由。

select X.q
from
(
select T.c.query('.') as q,
row_number() over(order by T.c) as rn
from @xml.nodes('/Fruits/*') T(c)
) as X
order by X.rn

不可能在 order by 中直接使用 T.c。尝试一下会给你

Msg 493, Level 16, State 1, Line 19
The column 'c' that was returned from the nodes() method cannot be used directly. It can only be used with one of the four XML data type methods, exist(), nodes(), query(), and value(), or in IS NULL and IS NOT NULL checks.

该错误没有提到它应该与 row_number 一起使用,但它确实可以,而且很可能是一个可能会被修复的错误,因此上面的代码将失败。但在 SQL Server 2012 之前,它工作得很好。

一种不依赖 row_number 的未记录使用而获得保证顺序的方法是使用一个数字表,您可以在其中按位置提取节点。

select T.c.query('.') as q
from Numbers as N
cross apply @xml.nodes('/Fruits/*[sql:column("N.Number")]') as T(c)
where N.Number between 1 and @xml.value('count(/Fruits/*)', 'int')
order by N.Number

关于sql-server - `nodes()` 方法是否保持文档顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17748012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com