Will TOP always return the same rows
I have written some code to move data into an archive table, 1000 rows at a time (SQL Server 2008 R2):
-- archive data
while (@QuitLoop = 0)
begin
begin transaction
insert into MyTransactionTable (...)
select top 1000 * from MyTransactionTable where DateOfSale < @ArchiveCutOffDate
delete top 1000 from MyTransactionTable where DateOfSale < @ArchiveCutOffDate
i开发者_运维知识库f (@@rowcount = 0) select @QuitLoop = 1
commit transaction
end
Will top always returns the same 1000 rows?
So the rows being inserted into the archive table are the same as the rows being deleted form the transaction table.
As you are using them no, they will not be guaranteed to return the same rows.
Why? Because you don't specify an order by
clause. It'll just be whatever 1000 records the engine decides are the 'top' ones that time around.
Also note that it's possible even if you specify an order by
that you still wouldn't get the same 1000 rows... if your order by is not selective enough that on the border of the 1000th item is a specific, definable order.
For example; if there are 1002 items with the same sorted value at the top, you don't know which 2 would not be included.
精彩评论