Row Offset in SQL Server

后端 未结 16 2602
醉酒成梦
醉酒成梦 2020-11-22 05:53

Is there any way in SQL Server to get the results starting at a given offset? For example, in another type of SQL database, it\'s possible to do:

SELECT * FR         


        
16条回答
  •  隐瞒了意图╮
    2020-11-22 06:17

    There is OFFSET .. FETCH in SQL Server 2012, but you will need to specify an ORDER BY column.

    If you really don't have any explicit column that you could pass as an ORDER BY column (as others have suggested), then you can use this trick:

    SELECT * FROM MyTable 
    ORDER BY @@VERSION 
    OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY
    

    ... or

    SELECT * FROM MyTable 
    ORDER BY (SELECT 0)
    OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY
    

    We're using it in jOOQ when users do not explicitly specify an order. This will then produce pretty random ordering without any additional costs.

提交回复
热议问题