SQL Server 2005 has a
ROW_NUMBER() function that can help with paging records for you database applications.
ROW_NUMBER() returns a sequential number, starting at 1, for each row returned in a resultset.
If I want the first page of 10 records from my log file sorted by ID, you can use the
ROW_NUMBER FUNCTION as follows:
With DynamicPagesEntities As
(
Select ROW_NUMBER() Over (Order By DynamicPageID) As Row,
DynamicPageID -- This should be the primary key / index for better performance
From dbo.dynamicPages
Where Valid = 1
)
Select dp.DynamicPageID,
dp.PageTitle,
dp.Valid
From DynamicPagesEntities de INNER JOIN dbo.dynamicPages dp ON de.DynamicPageID = dp.DynamicPageID
Where de.Row Between 1 AND 10
Order By de.Row Asc
(OR)
Other simple way of doing this is as follows. Displaying 2nd page from 11 to 20
Select dp.DynamicPageID,
dp.PageTitle,
dp.Valid
From (Select ROW_NUMBER() Over (Order By DynamicPageID) As Row, DynamicPageID,
PageTitle,
Valid from dbo.dynamicPages Where Valid = 1) dp
Where dp.Row Between 11 AND 20
Order By dp.Row Asc
Let me know if you have any other way of doing it, would love to know :D