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

后端 未结 5 1017
我寻月下人不归
我寻月下人不归 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 14:06

    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
    

提交回复
热议问题