Craig
Craig

Reputation: 18694

SQL Server Paging, with dynamic ordering?

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?

Upvotes: 2

Views: 1374

Answers (1)

RichardTheKiwi
RichardTheKiwi

Reputation: 107716

What you do instead is move the ORDER BY code into the ROW_NUMBER window function.

Like this example

SELECT * -- your columns
FROM
(
    SELECT *, ROWNUM = ROW_NUMBER() OVER (
    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
    )
    FROM TBL

) R
where ROWNUM between ((@pageNumber-1)*@PageSize +1) and (@pageNumber*@PageSize)

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.

Upvotes: 4

Related Questions