Paginate a recordset

Although SQL Server an Access support the TOP keyword to limit the amount of records returned, you cannot specify a starting value; making it unsuitable for use when paginating a recordset (ie displaying records over multiple pages, as in a web directory). Fortunately, ADO provides an alternative:

'create a recordset object
Set rItems = Server.CreateObject("ADODB.Recordset")

'set the cursor location and type
rItems.CursorLocation = 3' adUseClient
rItems.CursorType = 3 'adOpenStatic

'number of rows to cache at a time. Should be set to the same as PageSize
rItems.CacheSize = 10

'number of items to display per 'page'
rItems.PageSize = 10

'execute the SQL query, and keep the recordset open
'you cannot use the Execute statement for this.

rItems.Open sSQL, cConn

'check if empty
If rItems.EOF Then
    'no rows

    'set current page
    rItems.AbsolutePage = Request.QueryString("page")

    'get the total number of records
    nItemCount = rItems.RecordCount

    'get the number of pages
    nPageCount = rItems.PageCount

    'loop through an display the items in the recordset
    Do While Not rItems.EOF and nItem < rItems.PageSize

        'do something
        rItems.MoveNext 'move to the next record
        nItem=nItem+1 'increment count

End If

'close the recordset

'and destroy the object...
Set rItems = Nothing

You might also like...


James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Most software today is very much like an Egyptian pyramid with millions of bricks piled on top of each other, with no structural integrity, but just done by brute force and thousands of slaves” - Alan Kay