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

后端 未结 5 1013
我寻月下人不归
我寻月下人不归 2021-02-07 13:35

I want use OFFSET and Fetch in my SQL server 2012 query.But without any order by.I can not use order by.Because my sort order will be lost. How can I use OFFSET and Fetch withou

5条回答
  •  走了就别回头了
    2021-02-07 13:43

    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
    

提交回复
热议问题