Got more questions? Find advice on: SQL | XML | Regular Expressions | Windows
in Search
Welcome to AspAdvice Sign in | Join | Help

Justin Lovell's Blog

Mood: The Grumpy Coder

SQL Pagination -- the final solution

In a previous blog post of mine, I said that Cursors are slow. Little did I know that I was going to come up with an excellent paging solution that... ermm... involved cursors. This took some really abstract thinking to achieve the following script:

Declare @TotalRows int
Set @TotalRows = @StartRow + @RowCount

Declare @PK int
DECLARE @tmpTable TABLE (
    PK int NOT NULL PRIMARY KEY
)

Set RowCount @TotalRows

DECLARE PagingCursor CURSOR DYNAMIC READ_ONLY FOR
 Select PrimaryKey From LargeTable
   [WHERE CLAUSE]
  Order By PrimaryKey

Open PagingCursor
Fetch Relative @StartRow From PagingCursor Into @PK

while (@RowCount <> 0) And (@@Fetch_Status = 0)
begin
 Insert Into @tmpTable (PK)
  Values (@PK)

 Fetch Next From PagingCursor Into @PK
 Set @RowCount = @RowCount - 1
end

Close PagingCursor
Deallocate PagingCursor

Select LargeTable.* From LargeTable
 Join @tmpTable temp ON LargeTable.PrimaryKey = temp.PK
 Order By PrimaryKey

Set RowCount 0

The above is quite logical on how things work. So far, this is the fastest solution and best solution to the “generic” mark-up of paging results.

Sponsor
Published Wednesday, September 15, 2004 7:09 PM by jlovell
Filed under:

Comments

 

jlovell said:

Justin,
John Papa has series of articles on Paging and SQL. CHeck it out:
http://msdn.microsoft.com/msdnmag/issues/03/05/DataPoints/default.aspx

My two cents, Maxim

[www.ipattern.com do you?]
September 15, 2004 10:41 PM
 

jlovell said:

Thanks Maxim. However, if you have to benchmark up the SQL paging, you will find out that would be a great solution up to 100 pagings for a return of 20 records each go.

I am looking enterprise level paging. Ironically, given in the above paging criteria, both of them (the article and my solution) work at the same speed.
September 16, 2004 8:08 PM
 

jlovell said:

Justin, have you looked into the performance of the paging technique discussed here - http://tinyurl.com/3jtf4
November 14, 2004 10:22 AM
 

jlovell said:

June 9, 2005 11:41 PM
 

jlovell said:

No comments on the faster paging solution from the SQLTeam.com link? The cursor solution was much slower than the solution provided by a SQLTeam member.
June 15, 2005 10:57 PM
 

jlovell said:

I just haven't found the time to even look :). I just had a squiz there and I do have a thing or two just double-check up on. I'll probably write some unit tests to test out the performance when I get around to it.
June 16, 2005 8:53 PM
 

jlovell said:

Justin,
What are the limitations of this approach? Will this approach always work regardless of the uniquness of the sort columns? I hope you won't mind answering these for us :)
July 9, 2005 1:49 AM
 

TrackBack said:

November 17, 2004 2:33 PM
Anonymous comments are disabled