Paging through a dataset is always a requirement of any data oriented application. There are several solutions to implement paging. Some of them are client based and some are server based.
Every paging solution needs:
- Records of only selected page
- Total no. of records to calculate total of pages available
Whatever solution you implement, you will end up doing at least two queries, first to find total no. of records and secondly to find the records of your selected page.
In oneof my previous posts, I showed you the way of implementing paging by using Row_Number() function of SQL Server 2005. Today, I am showing you an excellent trick to get total of records and list of selected records in just one query. Following is the sample code to implement this logic. This code demonstrates the way you can implement paging very effectively without hitting the server twice. Note down the use of Count(*) OVER() functionality.
Use AdventureWorks
Go
–Change these two variable to parameters of your
–actual stored procedure
Declare @PageNumber int
Declare @PageSize int
–Assume we need page 6 i.e. records from 51-60
Select @PageNumber=6
Select @PageSize=10
–Select only those records which
–fit into a single page
Select Top(@PageSize) * from
(
Select
RowID=ROW_NUMBER() OVER (ORDER BY Name),
ProductID,Name,ProductNumber,ListPrice,
TotalRows=Count(*) OVER() –Count all records
from Production.Product
) A
Where A.RowId > ((@PageNumber-1)*@PageSize)