DataReader.NextResult 检索结果是否始终是相同的顺序
我有一个生成多个结果的 SELECT 查询,并且没有任何 ORDER BY 子句。 如果我多次执行此查询,然后使用 DataReader.NextResult() 迭代结果,是否可以保证以相同的顺序获得结果?
例如,如果我执行以下返回 199 行的查询:
SELECT * FROM products WHERE productid < 200
我是否总是会得到第一个结果,productid = 1 等等?
据我观察,它总是以相同的顺序返回结果,但我找不到有关此行为的任何文档。
==========================================
根据我的研究: 查看此博客 Conor 与 SQL。我实际上想问即使表中的数据保持不变(即没有更新或删除),查询结果是否会发生变化。但似乎在大表的情况下,当SQL Server采用并行性时,顺序可能会不同
I have a SELECT query that yields multiple results and do not have any ORDER BY clause.
If I execute this query multiple times and then iterate through results using DataReader.NextResult(), would I be guaranteed to get the results in the same order?
For e.g. if I execute the following query that return 199 rows:
SELECT * FROM products WHERE productid < 200
would I always get the first result with productid = 1 and so on?
As far as I have observed it always return the results in same order, but I cannot find any documentation for this behavior.
======================================
As per my research:
Check out this blog Conor vs. SQL. I actually wanted to ask if the query-result changes even if the data in table remains the same (i.e no update or delete). But it seems like in case of large table, when SQL server employees parallelism, the order can be different
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,要迭代 DataReader 中的行,您应该调用
阅读
,而不是NextResult
。调用
NextResult
如果您的查询有多个 SELECT 语句,则将移至下一个结果集。要回答您的问题,您不能依赖于此。
没有
ORDER BY
子句的查询将按照 SQL Server 的默认迭代顺序返回行。对于小型表,这通常是添加行的顺序,但这不能保证,并且可能随时更改。例如,如果表被索引或分区,则顺序将会不同。
First of all, to iterate the rows in a
DataReader
, you should callRead
, notNextResult
.Calling
NextResult
will move to the next result set if your query has multipleSELECT
statements.To answer your question, you must not rely on this.
A query without an
ORDER BY
clause will return rows in SQL Server's default iteration order.For small tables, this will usually be the order in which the rows were added, but this is not guaranteed and is liable to change at any time. For example, if the table is indexed or partitioned, the order will be different.
不,DataReader 将按照从 SQL 返回的顺序返回结果。如果不指定 ORDER BY 子句,则这将是它们在表中存在的顺序。
No, DataReader will return the results in the order they come back from SQL. If you don't specify an ORDER BY clause, that will be the order that they exist in the table.
有可能,甚至很可能它们总是以相同的顺序返回,但这并不能保证。该顺序由数据库服务器上的查询计划(至少在 SQL Server 中)确定。如果查询计划发生变化,顺序可能会改变。如果结果的顺序对数据处理很重要,则应始终使用 ORDER BY。
It is possible, perhaps even likely that they will always return in the same order, but this isn't guaranteed. The order is determined by the queryplan (at least in SQL Server) on the database server. If something changes that queryplan, the order could change. You should always use ORDER BY if the order of results is in anyway important to your processing of the data.