Implementing Paging and Dynamic Sorting on SQL 2005 databases

ROW_NUMBER() is a new function in SQL 2005 that returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

DECLARE @START int;
DECLARE @END int;
DECLARE @Sort nvarchar(100);
SET @Start=10;
SET @END=20;
SET @Sort=’LastName’;
SELECT *  FROM (SELECT ROW_NUMBER() over (
        ORDER BY CASE
            WHEN @Sort=’FirstName’ THEN FirstName
            WHEN @Sort=’LastName’ THEN LastName
            ELSE FirstName
        END) as R ,* From Students) as tbl
WHERE R BETWEEN @Start AND @End

Leave a comment

Please be polite and on topic. Your e-mail will never be published.

You must be logged in to post a comment.