What is the best way to paginate results in SQL Server

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

    MSDN: ROW_NUMBER (Transact-SQL)

    Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

    The following example returns rows with numbers 50 to 60 inclusive in the order of the OrderDate.

    WITH OrderedOrders AS
    (
        SELECT
            ROW_NUMBER() OVER(ORDER BY FirstName DESC) AS RowNumber, 
            FirstName, LastName, ROUND(SalesYTD,2,1) AS "Sales YTD"
        FROM [dbo].[vSalesPerson]
    ) 
    SELECT RowNumber, 
        FirstName, LastName, Sales YTD 
    FROM OrderedOrders 
    WHERE RowNumber > 50 AND RowNumber < 60;
    
      RowNumber FirstName    LastName               SalesYTD
      --- -----------  ---------------------- -----------------
      1   Linda        Mitchell               4251368.54
      2   Jae          Pak                    4116871.22
      3   Michael      Blythe                 3763178.17
      4   Jillian      Carson                 3189418.36
      5   Ranjit       Varkey Chudukatil      3121616.32
      6   José         Saraiva                2604540.71
      7   Shu          Ito                    2458535.61
      8   Tsvi         Reiter                 2315185.61
      9   Rachel       Valdez                 1827066.71
      10  Tete         Mensa-Annan            1576562.19
      11  David        Campbell               1573012.93
      12  Garrett      Vargas                 1453719.46
      13  Lynn         Tsoflias               1421810.92
      14  Pamela       Ansman-Wolfe           1352577.13
    

提交回复
热议问题