Generating Pagination in Sql Server 2005 using ROW_NUMBER() function
Method 1:
DECLARE @rowsPerPage int, @pageNum int, @startRow int, @endRow int SET @rowsPerPage = 10 SET @pageNum = 3 SET @startRow = ((@pageNum- 1) * @rowsPerPage)+1 SET @endRow = @startRow + @rowsPerPage -1 SELECT * FROM ( SELECT row_number() OVER (ORDER BY id) as resultNum, id FROM myTable ) as numberResults WHERE resultNum BETWEEN @startRow AND @endRow
Method 2 (Recommended Method):
SET @rowsPerPage = 10 SET @pageNum = 3 With SQLPaging As ( Select Top(@rowsPerPage * @pageNum) ROW_NUMBER() OVER (ORDER BY id) as resultNum, id FROM myTable ) select * from SQLPaging where resultNum > ((@pageNum - 1) * @rowsPerPage)
I didn't know the method 2. Very useful. Thanks from Chile
I saw both of your ways of paging in sql server 2005. Both code are much more efficient than we used to do earlier. I just wanted to make sure, why the second method that you have recommended in this article is efficient. My reason is: The second method is efficient because it extracts records beginning from the first record to only the records that are meant to be returned. while the first method of paging is less efficient because it extracts all the available records that matches the condition in select statement. I just wanted to know. Am i right. Please let me know. Thanks Randhir
Thanks Randhir, your reason is perfectly right.
Any particular reason why you would recommend the second method rather than the first one?
Thumbs up to Method 2. Was longing for exactly for code of this efficiency. Good thinking. Keep up the excellent work...