What is the best way to paginate results in SQL Server

前端 未结 19 2510
我寻月下人不归
我寻月下人不归 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:04

    From SQL Server 2012, we can use OFFSET and FETCH NEXT Clause to achieve the pagination.

    Try this, for SQL Server:

    In the SQL Server 2012 a new feature was added in the ORDER BY clause, to query optimization of a set data, making work easier with data paging for anyone who writes in T-SQL as well for the entire Execution Plan in SQL Server.

    Below the T-SQL script with the same logic used in the previous example.

    --CREATING A PAGING WITH OFFSET and FETCH clauses IN "SQL SERVER 2012"
    DECLARE @PageNumber AS INT, @RowspPage AS INT
    SET @PageNumber = 2
    SET @RowspPage = 10 
    SELECT ID_EXAMPLE, NM_EXAMPLE, DT_CREATE
    FROM TB_EXAMPLE
    ORDER BY ID_EXAMPLE
    OFFSET ((@PageNumber - 1) * @RowspPage) ROWS
    FETCH NEXT @RowspPage ROWS ONLY;
    

    TechNet: Paging a Query with SQL Server

提交回复
热议问题