SQL Server : rows in table changed their order

我的未来我决定 提交于 2021-02-05 09:45:03

问题


I've created table with number like this: How to find gaps of data and insert NULL data points instead having gap

;WITH
Pass0 as (select 1 as C union all select 1), --2 rows
Pass1 as (select 1 as C from Pass0 as A, Pass0 as B),--4 rows
Pass2 as (select 1 as C from Pass1 as A, Pass1 as B),--16 rows
Pass3 as (select 1 as C from Pass2 as A, Pass2 as B),--256 rows
Pass4 as (select 1 as C from Pass3 as A, Pass3 as B),--65536 rows
Pass5 as (select 1 as C from Pass4 as A, Pass4 as B),--4,294,967,296 rows
Tally as (select row_number() over(order by C) as Number from Pass5)
select Number INTO dbo.Numbers from Tally where Number <= 1000000

It worked like a charm, but after months of running SQL Server, some SQL service restarts etc., my database was recovering for few minutes.

I am not sure if my table broke after restore time, however I've noticed at some point that my rows are not in order.

MIN is 1,
MAX is 1000000,
AVG is 500000

So it looks like still all rows are in place, but the last row is not the 1000000.

Also after first 3332 rows it loses an order and the next row Number is 49029.

I use that table to find gaps in data and insert NULLs.

My application that's based on that table failed. I don't have any checks on application side if that table is in order, but that was my assumption. I am using SQL engine, so I should be guaranteed.

Any ideas what could happen?


回答1:


Rows in a table can not change their order because..... they do not have an order. The order of a set is not defined. Unless your select has an ORDER BY clause the order it is returned is random and can change even between two calls.

That is fundamental SQL.

You want an order, put an order into the SELECT statement.



来源:https://stackoverflow.com/questions/22422704/sql-server-rows-in-table-changed-their-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!