SQL Server query with pagination and count

前端 未结 5 1010
一生所求
一生所求 2020-12-12 13:54

I want to make a database query with pagination. So, I used a common-table expression and a ranked function to achieve this. Look at the example below.

decla         


        
5条回答
  •  星月不相逢
    2020-12-12 14:15

    What if you calculate the count beforehand?

    declare @pagenumber int = 2;
    declare @pagesize int = 3;
    declare @total int;
    
    SELECT @total = count(*)
    FROM @table
    
    with query as
    (
       select name, ROW_NUMBER() OVER(ORDER BY name ASC) as line from @table
    )
    select top (@pagesize) name, @total total from query
    where line > (@pagenumber - 1) * @pagesize
    

    Another way, is to calculate max(line). Check the link

    Return total records from SQL Server when using ROW_NUMBER

    UPD:

    For single query, check marc_s's answer on the link above.

        with query as
        (
           select name, ROW_NUMBER() OVER(ORDER BY name ASC) as line from @table
        )
        select top (@pagesize) name, 
           (SELECT MAX(line) FROM query) AS total 
        from query
        where line > (@pagenumber - 1) * @pagesize
    

提交回复
热议问题