In Sql Server 2014 ORDER BY clause with OFFSET FETCH NEXT returns weird results

前端 未结 2 1483
我寻月下人不归
我寻月下人不归 2021-01-12 21:34

I am currently using Sql Server 2014 Professional and the current version is (12.0.4100). I have a View and I am trying to SELECT 10 rows with specific offset.
My View i

2条回答
  •  不知归路
    2021-01-12 22:29

    The documentation explains:

    To achieve stable results between query requests using OFFSET and FETCH, the following conditions must be met:

    . . .

    1. The ORDER BY clause contains a column or combination of columns that are guaranteed to be unique.

    What happens in your case is that BeginTime is not unique. Databases in general -- and SQL Server in particular -- do not implement stable sorts. A stable sort is one where the rows are in the same order when the keys are the same. This is rather obvious, because tables and result sets represent unordered sets. They have no inherent ordering.

    So, you need a unique key to make the sort stable. Given your data, this would seem to be either duration, name, or both:

    SELECT * 
    ROM View_Name
    ORDER BY BeginTime ASC, Duration, Name
    OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
    

提交回复
热议问题