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.
- 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.
- 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.
- 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