What is the best way to paginate results in SQL Server

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

    This bit gives you ability to paginate using SQL Server, and newer versions of MySQL and carries the total number of rows in every row. Uses your pimary key to count number of unique rows.

    WITH T AS
    (  
      SELECT TABLE_ID, ROW_NUMBER() OVER (ORDER BY TABLE_ID) AS RN
      , (SELECT COUNT(TABLE_ID) FROM TABLE) AS TOTAL 
      FROM TABLE (NOLOCK)
    )
    
    SELECT T2.FIELD1, T2.FIELD2, T2.FIELD3, T.TOTAL 
    FROM TABLE T2 (NOLOCK)
    INNER JOIN T ON T2.TABLE_ID=T.TABLE_ID
    WHERE T.RN >= 100
    AND T.RN < 200
    

提交回复
热议问题