Pagination through Sql query

0

Please login or register to vote for this query.

(click on this box to dismiss)

http://stackoverflow.com/questions/13207520/pagination-through-sql-query

The Workplace Meta

Q&A about the site for members of the workforce navigating the professional setting

declare @t table
(
	Id int,
	Name VARCHAR(50)
);
DECLARE @PageIndex int;
DECLARE @PageSize int;
SET @PageIndex = 1;
SET @PageSize = 2;
INSERT INTO @t VALUES(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7,'g');

;With ranked AS   --- Or you can make it a view
(
   SELECT ROW_NUMBER() OVER(ORDER BY Name) AS RowNum,  * 
   FROM @t
)
SELECT *   --Your fields here
FROM Ranked
WHERE RowNum BETWEEN ((@PageIndex - 1) * @PageSize + 1)
    AND (@PageIndex * @PageSize)
ORDER BY Name

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results