August 5, 2008

Paging of SQL Server records

Filed under: .net,sql server Himanshu @ 6:29 am

In one of my ASP.NET, SQL Server project, we were expected to provide paging in the ASP.NET GridView. Microsoft’s very common sample will do this using Dataset filled with all records. If someone is doing GridView paging, s/he is doing it not waste server’s or client’s precious resources, Isn’t it?

To me, it make more sense to do paging of records being fetched in server memory along with view paging. What if table in question has more then 100,000 (1 lack) records?

Digging a bit further, I found a resource which explains how to do paging of records being sent from stored procedure. But it was expecting to have auto identity as primary key in the table. And we were so fortunate that we couldn’t have db design such that we can afford to have auto identity primary key, and so that solution to the paging problem. On doing some more finding, we all agreed to a solution that is described below. It’s not fully optimized, as it do not have any optimization for SQL Server to prepare result sets. But worked for our need in specific project as even in 100,000 records it was working very fast.

In our solution, stored procedure that will fetch records from table and return to caller will needs to have two addition parameters, @RowIndexFrom and @RowIndexTo

Getting customers by page will look like following,

CREATE PROCEDURE [dbo].[GetCustomersPage]
(
    @RowIndexFrom int,
    @RowIndexTo int
)
AS
BEGIN
    SET NOCOUNT ON;

    WITH IndexedCustomers AS
    (
        SELECT
            ROW_NUMBER() OVER (ORDER BY Id) AS rowIndex,
            Customers.*
        FROM
            Customers
    )
    SELECT * FROM IndexedCustomers WHERE rowIndex BETWEEN @RowIndexFrom AND @RowIndexTo

    SELECT COUNT(*)
    FROM
        Customers
END
GO

 

The stored procedure returns two result set, first will be records for given page (defined by different between @RowIndexFrom and @RowIndexTo parameters). And the second result set will give total number of records for give query. Second result set will help preparing pages list. So, if first page needs to be retrieved of page size 10, parameter values should be 1 and 10 respectively.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress