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

Software Quality Assurance and Testing Meta

Q&A about the site for software quality control experts, automation engineers, and software testers

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

;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 to main site
loading Hold tight while we fetch your results