Paging in MS SQL 2005

Paging results from an SQL query can sometimes be quite difficult. MySQL has for a long time supported 'LIMIT x,y' to aid this, however with Microsoft SQL it has always been a bit more difficult. With MS SQL 2005 thing are a little easier. Try the snippet below, based on the AdventureWorks sample database included with SQL 2005.

PAGE_SIZE is the number of results you want per page
PAGE_COUNT is which page you want to display

SQL:
  1. DECLARE @PAGE_SIZE int
  2. SELECT @PAGE_SIZE = 15
  3. DECLARE @PAGE_COUNT int
  4. SELECT @PAGE_COUNT = 3
  5. SELECT TOP (@PAGE_SIZE) * FROM (
  6.    SELECT  EmployeeID, BirthDate,
  7.    ROW_NUMBER() OVER (ORDER BY BirthDate ASC) AS [Result Number]
  8.    FROM HumanResources.Employee) innerSel
  9. WHERE [Result Number]> ((@PAGE_COUNT - 1) * @PAGE_SIZE)
  10. ORDER BY [Result Number]

Leave a Comment

Name

Mail (will not be published)

Website

Comment