I found this nice example of doing paging in SQL Server, however, I need to do some dynamic ordering. That is, the user passes in an integer, which then gets used to do the ordering, like this:
ORDER BY
CASE WHEN @orderBy = 1 THEN DateDiff(ss, getdate(), received_date) --oldest
WHEN @orderBy = 2 THEN DateDiff(ss, received_date, getdate()) --newest
WHEN @orderBy = 3 THEN message_id --messageid
WHEN @orderBy = 4 THEN LEFT(person_reference, LEN(person_reference)-1) --personid
END
Is it possible to do paging, with this form of dynamic ordering?
What you do instead is move the ORDER BY code into the ROW_NUMBER window function.
Like this example
The main problem with the complex ORDER BY and the windowing function is that you end up fully materializing the rownum against all rows before returning just one page.