Efficient Paging Code for MS SQL Server 2005
Posted by on Mar 11th, 2008
2008
Mar 11
As a web developer I often encounter the need to page results for better UI experience.
Normally with an SQL ANSI 92 compliant database engine all you had to do was specify how many rows you wanted returned and how many rows to skip, something like:
Which translates to skip 10 rows and then return next 10 rows.
Unfortunately, there was no such thing in MS SQL Server. So after two hours of searching I encountered function called Row_Number.
As per the SQL Book online, the Row_Number() function returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
Anyhow, here is how the new query looked like:
The SQL was longer but it had same desired effect. Anyhow it’s getting late, hope I was of help.
Normally with an SQL ANSI 92 compliant database engine all you had to do was specify how many rows you wanted returned and how many rows to skip, something like:
SELECT First 10 Skip 10 * FROM table1 ORDER BY Column1
Which translates to skip 10 rows and then return next 10 rows.
Unfortunately, there was no such thing in MS SQL Server. So after two hours of searching I encountered function called Row_Number.
As per the SQL Book online, the Row_Number() function returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
Anyhow, here is how the new query looked like:
SELECT *
FROM (
SELECT Row_Number() OVER(ORDER BY Column1) AS Row,
*
FROM table1
) WHERE Row Between 10 AND 20
ORDER BY Column1
The SQL was longer but it had same desired effect. Anyhow it’s getting late, hope I was of help.