What is the best way to paginate results in SQL Server

前端 未结 19 2464
我寻月下人不归
我寻月下人不归 2020-11-22 01:36

What is the best way (performance wise) to paginate results in SQL Server 2000, 2005, 2008, 2012 if you also want to get the total number of results (before paginating)?

19条回答
  •  迷失自我
    2020-11-22 02:05

    Finally, Microsoft SQL Server 2012 was released, I really like its simplicity for a pagination, you don't have to use complex queries like answered here.

    For getting the next 10 rows just run this query:

    SELECT * FROM TableName ORDER BY id OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;
    

    https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql#using-offset-and-fetch-to-limit-the-rows-returned

    Key points to consider when using it:

    • ORDER BY is mandatory to use OFFSET ... FETCH clause.
    • OFFSET clause is mandatory with FETCH. You cannot use ORDER BY ... FETCH.
    • TOP cannot be combined with OFFSET and FETCH in the same query expression.

提交回复
热议问题