Thursday, October 06, 2011

Add Skip and Take parameters along with ROW_NUMBER to Stored Procedures for Paginating

The example below is based on what Linq automagically does for you when it dynamically constructs a T-SQL statement.

Three new aspects for paging, compared to a normal query, include.

  1. Add the command ROW_NUMBER() OVER(ORDER BY SomeColumn[s]) to your query to get an ordered index of records the way you want them 
    • the down side is you cannot sort by different columns in your app.
  2. Give that query an alias/name, [InsideQuery] in my example below (this won't work if you don't, even though the alias is never used), and wrap it with a SELECT * FROM, a succint way of creating a temporary table without having to create a temporary table as suggested in older examples.
  3. Now you can use the Row Number BETWEEN statment on the outer select --Row Number wasn't available on the inside select statement to perform the BETWEEN, but it is on the outside...
 DECLARE @Skip int = 0 	, @Take int = 5  SELECT * FROM	( 				SELECT ROW_NUMBER() OVER(ORDER BY Company) AS [RowNum], CoID, Company, CompanyURL  				FROM ezpl8_Companies  			) AS [InsideQuery]

WHERE [RowNum] BETWEEN (@Skip * @Take) + 1 AND (@Skip + 1) * @Take


Young Roofers

Young Roofers
Men Making

Fly. Be Free.

Fly. Be Free.
Man Ready to Hang ... Glide

Burke

Burke
A Man in the Making - 12 years old

Blackwater

Blackwater
A Man in the Mud