How do I page results in SQL Server 2005?
I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method?
What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on.
Any help would be much appreciated.
You can use
the Row_Number()
function. Its used as follows:From which it will yield a result set with a
RowID
field which you can use to page between.etc
If you're trying to get it in one statement (the total plus the paging). You might need to explore SQL Server support for the partition by clause (windowing functions in ANSI SQL terms). In Oracle the syntax is just like the example above using row_number(), but I have also added a partition by clause to get the total number of rows included with each row returned in the paging (total rows is 1,262):
Note that I have where owner = 'CSEIS' and my partition by is on owner. So the results are:
The accepted answer for this doesn't actually work for me...I had to jump through one more hoop to get it to work.
When I tried the answer
it failed, complaining that it didn't know what RowID was.
I had to wrap it in an inner select like this:
and then it worked.
When I need to do paging, I typically use a temporary table as well. You can use an output parameter to return the total number of records. The case statements in the select allow you to sort the data on specific columns without needing to resort to dynamic SQL.
I believe you'd need to perform a separate query to accomplish that unfortionately.
I was able to accomplish this at my previous position using some help from this page: Paging in DotNet 2.0
They also have it pulling a row count seperately.
Here's what I do for paging: All of my big queries that need to be paged are coded as inserts into a temp table. The temp table has an identity field that will act in a similar manner to the row_number() mentioned above. I store the number of rows in the temp table in an output parameter so the calling code knows how many total records there are. The calling code also specifies which page it wants, and how many rows per page, which are selected out from the temp table.
The cool thing about doing it this way is that I also have an "Export" link that allows you to get all rows from the report returned as CSV above every grid in my application. This link uses the same stored procedure: you just return the contents of the temp table instead of doing the paging logic. This placates users who hate paging, and want to see everything, and want to sort it in a million different ways.