T-SQL: How to do SQL Server paging with ROW_NUMBER()?

DECLARE @PageNum AS INT;

DECLARE @PageSize AS INT;

SET @PageNum = 2;

SET @PageSize = 10;

 

WITH OrdersRN AS

(

    SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum

          ,OrderID

          ,OrderDate

          ,CustomerID

          ,EmployeeID

      FROM dbo.Orders

)

 

SELECT *

FROM OrdersRN

WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1

      AND @PageNum * @PageSize

ORDER BY OrderDate,OrderID;

 

 


Thursday, November 22, 2007 | Add Comment

New Comment

Your Name:
Email (for internal use only):
Subject:
Comment:
 
Code above:

Categories

Recent Tweets

  • Creating a Microsoft .NET Compact Framework-based Animation Control http://t.co/P92rCZ4
  • Now you can jailbrake your iphone from browser: http://bit.ly/91Nm7S. It is legal, but voids your iPhone warranty.
  • iPhone jailbreaking and Android rooting get DMCA exemption http://bit.ly/bCmEEA
  • Here is excellent tool for development of JQuery scripts, it is called jsshell: http://bit.ly/72wsQz. It is Google Chrome extension.

Valid XHTML 1.0 Transitional