How to use OFFSET and Fetch without Order by in SQL Server

百般思念 提交于 2019-12-03 10:50:32

By adding an identity column to the temp table variable

    declare @TempTable table([some columns], rownr int identity(1,1) )

    INSERT INTO @TempTable [some columns]  
    select [some columns] from table1  order by col1 

    INSERT INTO @TempTable [same columns]
    select [some columns] from table2 order by col2

An automatic incrementing number is added for each row, in the order in which they are added to the temp table. The inserts don't need to fill this column, so the inserts can remain as they are. The identity column can then be used for the order by:

 select * from @TempTable Order by rownr OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY

There is an even simpler way of providing a dummy ORDER BY clause:

select * from @TempTable ORDER BY(SELECT NULL) OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY

You cannot avoid using the required syntax of a ORDER BY with OFFSET and FETCH.

It is however possible to disassociate the ORDER BY clause that you must provide in order to perform paging from the natural table order created by the record insert process.

Using the solution below you do not have to make any changes to the underlying table either

Select 0 as TempSort, T.* From MyTable T ORDER BY TempSort OFFSET 2 ROWS FETCH NEXT 3 ROWS

After research and according to comments, The clear and summary answer is : "There is no way!"

But you can remain your sort order with row_number(). So I provided a new tested query that remain the sort order of temp table(final table) with OFFSET and FETCH clause.

    INSERT INTO @TempTable [some columns]  
    select [some columns],row_number() OVER (order by col1) row from table1 order by col1 

    declare @maxrow int
    select @maxrow=max(rn) from @TempTable

    INSERT INTO @TempTable [same columns]
    select [some columns],((row_number() OVER (order by col2)) + @maxrow) row from table2 order by col2

    select * from @TempTable Order by row  OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY

Offset/Fetch requires an order by clause. You can use the CURRENT_TIMESTAMP to bypass this requirement if you don't want to go by any order. I am not sure but, this should return rows based on the order of storage (clustered index maybe)

So changing your code to this should solve the issue -

INSERT INTO @TempTable [some columns]  
select [some columns] from table1 order by col1 
INSERT INTO @TempTable [same columns]
select [some columns] from table2 order by col2
select * from @TempTable **order by current_timestamp** OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!