Getting a Subset of Records along with Total Record Count

后端 未结 2 1458
长情又很酷
长情又很酷 2021-02-09 21:38

I\'m working on returning a recordset from SQL Server 2008 to do some pagination. I\'m only returning 15 records at a time, but I need to have the total number of matches along

2条回答
  •  孤街浪徒
    2021-02-09 22:06

    Here is what I have done (and its just as fast, no matter which records I return):

    --Parameters include:
    @pageNum int = 1,
    @pageSize int = 0,
    
    
    
    DECLARE 
        @pageStart int,
        @pageEnd int
    
    SELECT
        @pageStart = @pageSize * @pageNum - (@pageSize - 1),
        @pageEnd = @pageSize * @pageNum;
    
    
    SET NOCOUNT ON;
    WITH tempTable AS (
        SELECT
            ROW_NUMBER() OVER (ORDER BY FirstName ASC) AS RowNumber,
            FirstName
            , LastName
        FROM People
        WHERE Active = 1
    )
    
    SELECT
        (SELECT COUNT(*) FROM tempTable) AS TotalRows,
        *
    FROM tempTable
    WHERE @pageEnd = 0
    OR RowNumber BETWEEN @pageStart AND @pageEnd
    ORDER BY RowNumber
    

提交回复
热议问题