Chris Ongsuco's Weblog
Information Technology, business, life, food...

SQL Server 2005 Paging Sample

Wednesday, November 02, 2005 7:57 AM
Just playing around....


declare @Page int, @PageSize int

           

set @Page = 1;

set @PageSize = 10;

 

with PagedResult

  as (select ROW_NUMBER() over (order by PersonID) as RowNum, *

    from Table1)

  select * from PagedResult

  where RowNum between

      case when @Page > 1 then (@PageSize * @Page) - @PageSize + 1

            else @Page end

                        and @PageSize * @Page

  order by PersonID

[EDITED: For SQL Server 2005 RTM]

Feedback

# re: SQL Server 2005 Paging Sample

Saved me some time, works like a charm.

Thx! 10/15/2006 5:19 PM | Oscar Aagren

# re: SQL Server 2005 Paging Sample

Whenever paging is required, usually the total count of items matching the criteria (before filtering) is also needed to know exactly how many pages the search is going to have.

I have seen lots of examples showing the use of the Row_Number() function, but no examples of getting the total number of items affected by the inner query, in your example:

select ROW_NUMBER() over (order by PersonID) as RowNum, * from Table1

I was playing around with the Row_Number function and figured out a way to get the total count:

select max(RowNum) from (select Row_Number() over (order by PersonID) as RowNum from Table1) as T1

Although it produces the required result, but I'm not sure if this is the most efficient way to do it, as the entire query is repeated.

I would appreciate your thought on this.

Thanks
7/25/2007 6:35 AM | Yasser Abbasi

# re: SQL Server 2005 Paging Sample

You can use the statement below to get the total record count:

union all
select max(RowNum), null as field1, null as field2,... from PagedResult 1/7/2008 3:12 PM | helper

# re: SQL Server 2005 Paging Sample

How do you get the total records over all pages using this structure? 1/27/2009 1:34 AM | Stephan Peters

Post a comment