Paging with Oracle and sql server and generic paging method

前端 未结 7 1086
予麋鹿
予麋鹿 2020-12-17 00:29

I want to implement paging in a gridview or in an html table which I will fill using ajax. How should I write queries to support paging? For example if pagesize is 20 and wh

相关标签:
7条回答
  • 2020-12-17 01:27

    As others have suggested, you can use rownum in Oracle. It's a little tricky though and you have to nest your query twice.

    For example, to paginate the query

    select first_name from some_table order by first_name
    

    you need to nest it like this

    select first_name from
      (select rownum as rn, first_name from
        (select first_name from some_table order by first_name)
      ) where rn > 100  and rn <= 200
    

    The reason for this is that rownum is determined after the where clause and before the order by clause. To see what I mean, you can query

    select rownum,first_name from some_table order by first_name
    

    and you might get

    4   Diane
    2   Norm
    3   Sam
    1   Woody
    

    That's because oracle evaluates the where clause (none in this case), then assigns rownums, then sorts the results by first_name. You have to nest the query so it uses the rownum assigned after the rows have been sorted.

    The second nesting has to do with how rownum is treated in a where condition. Basically, if you query "where rownum > 100" then you get no results. It's a chicken and egg thing where it can't return any rows until it finds rownum > 100, but since it's not returning any rows it never increments rownum, so it never counts to 100. Ugh. The second level of nesting solves this. Note it must alias the rownum column at this point.

    Lastly, your order by clause must make the query deterministic. For example, if you have John Doe and John Smith, and you order by first name only, then the two can switch places from one execution of the query to the next.

    There are articles here http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html and here http://www.oracle.com/technology/oramag/oracle/07-jan/o17asktom.html. Now that I see how long my post is, I probably should have just posted those links...

    0 讨论(0)
提交回复
热议问题