简体   繁体   中英

MS sql limit statment without order by and without top

I've an ORM layer that can communicates with several DBs, MYSQL,ORACLE,MS SQL and
I'am usign pagging in my applications, what i didn't know that i can get results
as pages straightfully from the query, so am updating the ORM layer to fit the 3 DBs
I mentioned.


In MYSQL SELECT * FROM myTable limit 5,5
In ORACLE SELECT * FROM ( SELECT * FROM myTable as t WHERE rownum < 100 ) WEHRE rownum > 10
But in MS SQL I cant find a way to get of the ORDER BY in the query

I apologize for any syntax errors in the queries, they are from memory.

My question is, is there any way to get rid of the ORDER BY and get paging capabilities for MS SQL

Please re-think what you are doing here.
No matter what database engine you're using, it makes absolutely no sense to try to get rid of ORDER BY when you want to use paging.

Rows in relational databases don't have a fixed order, you need to specify an ORDER BY clause if you want to receive rows in a certain order.
If you don't specify an ORDER BY clause, the database engine will return the rows in a random order. Often the order looks sensible (like, ordered by the primary key) and if you run the same query more than one time, the order might really be the same.

But in reality, this is all random, and you can't rely on this "pseudo-order" making any sense or being the same on each query.
So paging without specifying the order by yourself makes absolutely no sense.

Try

SELECT 
  * 
FROM 
  ( SELECT *,ROW_NUMBER() OVER (ORDER BY <some_col>) as rownum FROM myTable ) t 
WHERE rownum >= UpperLimit AND  rownum <= LowerLimit

Replace <some_col> with some column in your table that defines the order in which you want to page through your data.

I am not sure what the problem is. You can write:

select TOP 10 * from T

This works fine.

This usually does not make sense because the specific order is not guaranteed. It can even change from query to query.

But it can make sense if all you care about is to get any 10 records from a particular table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM