SQL Server分页,动态排序?

时间:2011-02-23 00:22:38

标签: sql sql-server-2005 sql-order-by paging

我发现this nice example在SQL Server中进行分页,但是,我需要做一些动态排序。也就是说,用户传入一个整数,然后习惯于进行排序,如下所示:

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

是否可以使用这种形式的动态排序进行分页?

1 个答案:

答案 0 :(得分:4)

您要做的是将ORDER BY代码移动到ROW_NUMBER窗口函数中。

就像这个例子一样

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)

复杂的ORDER BY和窗口函数的主要问题是,在返回一个页面之前,最终会对所有行完全实现rownum。