What is the best way to paginate results in SQL Server

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

    The best way for paging in sql server 2012 is by using offset and fetch next in a stored procedure. OFFSET Keyword - If we use offset with the order by clause then the query will skip the number of records we specified in OFFSET n Rows.

    FETCH NEXT Keywords - When we use Fetch Next with an order by clause only it will returns the no of rows you want to display in paging, without Offset then SQL will generate an error. here is the example given below.

    create procedure sp_paging
    (
     @pageno as int,
     @records as int
    )
    as
    begin
    declare @offsetcount as int
    set @offsetcount=(@pageno-1)*@records
    select id,bs,variable from salary order by id offset @offsetcount rows fetch Next @records rows only
    end
    

    you can execute it as follow.

    exec sp_paging 2,3
    

提交回复
热议问题