T-SQL: Paging with ROW_NUMBER()

Refrence: http://blogs.x2line.com/al/archive/2005/11/18/1323.aspx

T-SQL: Paging with ROW_NUMBER()

In MSSQL 2000 we used to do paging either by dynamic sql or by some advanced techniques like the example with rowcount. In MSSQL 2005 with the introduction of ROW_NUMBER function life is a lot easier.

DECLARE @PageNum AS INT;

DECLARE @PageSize AS INT;

SET @PageNum = 2;

SET @PageSize = 10;

WITH OrdersRN AS

(

SELECT ROW_NUMBER() OVER(ORDER BY IncidentId) AS RowNum

,*

FROM dbo.ExtendedResultsFirewallIncidents

)

SELECT *

FROM OrdersRN

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

AND @PageNum * @PageSize

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s