What is the best way to paginate results in SQL Server

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

    Use case wise the following seem to be easy to use and fast. Just set the page number.

    use AdventureWorks
    DECLARE @RowsPerPage INT = 10, @PageNumber INT = 6;
    with result as(
    SELECT SalesOrderDetailID, SalesOrderID, ProductID,
    ROW_NUMBER() OVER (ORDER BY SalesOrderDetailID) AS RowNum
    FROM Sales.SalesOrderDetail
    where 1=1
    )
    select SalesOrderDetailID, SalesOrderID, ProductID from result
    WHERE result.RowNum BETWEEN ((@PageNumber-1)*@RowsPerPage)+1
    AND @RowsPerPage*(@PageNumber)
    

    also without CTE

    use AdventureWorks
    DECLARE @RowsPerPage INT = 10, @PageNumber INT = 6
    SELECT SalesOrderDetailID, SalesOrderID, ProductID
    FROM (
    SELECT SalesOrderDetailID, SalesOrderID, ProductID,
    ROW_NUMBER() OVER (ORDER BY SalesOrderDetailID) AS RowNum
    FROM Sales.SalesOrderDetail
    where 1=1
     ) AS SOD
    WHERE SOD.RowNum BETWEEN ((@PageNumber-1)*@RowsPerPage)+1
    AND @RowsPerPage*(@PageNumber)
    

提交回复
热议问题