zoukankan      html  css  js  c++  java
  • What is the best way to paginate results in SQL Server

    Getting the total number of results and paginating are two different operations. For the sake of this example, let's assume that the query you're dealing with is

    SELECT * FROM Orders WHERE OrderDate >= '1980-01-01' ORDER BY OrderDate

    In this case, you would determine the total number of results using:

    SELECT COUNT(*) FROM Orders WHERE OrderDate >= '1980-01-01'

    ...which may seem inefficient, but is actually pretty performant, assuming all indexes etc. are properly set up.

    Next, to get actual results back in a paged fashion, the following query would be most efficient:

    SELECT  *
    FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY OrderDate ) AS RowNum, *
              FROM      Orders
              WHERE     OrderDate >= '1980-01-01'
            ) AS RowConstrainedResult
    WHERE   RowNum >= 1
        AND RowNum < 20
    ORDER BY RowNum

    This will return rows 1-19 of the original query. The cool thing here, especially for web apps, is that you don't have to keep any state, except the row numbers to be returned.

  • 相关阅读:
    java反射小练习
    Set与list测试
    关于用户界面
    自定义标签打包使用问题
    jsp中获取当前访问路径
    LeetCode 汇总
    LeetCode 46. 全排列
    LeetCode 40.组合总和II
    LeetCode 39.组合总和
    LeetCode 37.解数独
  • 原文地址:https://www.cnblogs.com/jrmy/p/14316362.html
Copyright © 2011-2022 走看看