What is the best way to paginate results in SQL Server

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

    For the ROW_NUMBER technique, if you do not have a sorting column to use, you can use the CURRENT_TIMESTAMP as follows:

    SELECT TOP 20 
        col1,
        col2,
        col3,
        col4
    FROM (
        SELECT 
             tbl.col1 AS col1
            ,tbl.col2 AS col2
            ,tbl.col3 AS col3
            ,tbl.col4 AS col4
            ,ROW_NUMBER() OVER (
                ORDER BY CURRENT_TIMESTAMP
                ) AS sort_row
        FROM dbo.MyTable tbl
        ) AS query
    WHERE query.sort_row > 10
    ORDER BY query.sort_row
    

    This has worked well for me for searches over table sizes of even up to 700,000.

    This fetches records 11 to 30.

提交回复
热议问题