Best paging solution using SQL Server 2005?

前端 未结 3 1522
别那么骄傲
别那么骄傲 2020-12-09 05:58

What is the most efficient paging solution using SQL Server 2005 against a table with around 5,000-10,000 rows? I\'ve seen several out there but nothing comparing them.

3条回答
  •  情书的邮戳
    2020-12-09 06:54

    For a table that size, use a Common-Table Expression (CTE) and ROW_NUMBER; use a small function to calculate the records to bring back based on @PageNumber and @PageSize variables (or whatever you want to call them). Simple example from one of our stored procedures:

    -- calculate the record numbers that we need
    
    DECLARE @FirstRow INT, @LastRow INT
    SELECT  @FirstRow   = ((@PageNumber - 1) * @PageSize) + 1,
            @LastRow    = ((@PageNumber - 1) * @PageSize) + @PageSize
    
    ;
    WITH CTE AS
    (
        SELECT [Fields]
               , ROW_NUMBER() OVER (ORDER BY [Field] [ASC|DESC]) as RowNumber 
        FROM [Tables]
        WHERE [Conditions, etc]
    )
    SELECT * 
           -- get the total records so the web layer can work out
           -- how many pages there are
           , (SELECT COUNT(*) FROM CTE) AS TotalRecords
    FROM CTE
    WHERE RowNumber BETWEEN @FirstRow AND @LastRow
    ORDER BY RowNumber ASC
    

提交回复
热议问题