10

我有以下 SP 用于对新闻文章列表进行分页。正如您可能猜到的,@count是要返回的行数,@start是从中选择行的索引(按内部查询排序),@orderby表示要排序的列,并@orderdir表示是按一个方向排序还是按另一个方向排序。在我添加参数之前,我的原始查询在 这里。@orderdir

ALTER PROCEDURE [mytable].[news_editor_paginate]
    @count int,
    @start int,
    @orderby int,
    @orderdir int
AS 
BEGIN
    SET NOCOUNT ON; 
    SELECT TOP (@count) * FROM 
    (  
        SELECT ne.*,n.publishstate, 
            (CASE WHEN @orderdir = 1 THEN
                ROW_NUMBER() OVER (
                    ORDER BY                    
                        CASE WHEN @orderby = 0 THEN ne.[time] END DESC,
                        CASE WHEN @orderby = 1 THEN ne.lastedit END DESC,    
                        CASE WHEN @orderby = 2 THEN ne.title END ASC
                    )
            WHEN @orderdir = 2 THEN
                ROW_NUMBER() OVER (
                    ORDER BY                    
                        CASE WHEN @orderby = 0 THEN ne.[time] END ASC,    
                        CASE WHEN @orderby = 1 THEN ne.lastedit END ASC,
                        CASE WHEN @orderby = 2 THEN ne.title END DESC
                    )
                END
            ) AS num
            FROM news_edits AS ne
            LEFT OUTER JOIN news AS n
            ON n.editid = ne.id 
        ) 
     AS a
    WHERE num > @start
END

现在实际上没有任何问题,但@orderby参数不起作用。如果提供 1 作为@orderdir参数,它将给我完全相同的结果,就像我提供 2 作为该参数一样。

4

2 回答 2

21

不会在每一行上评估行号,但是 case 语句是这样的,所以不管是什么情况,你都会被 rownum 卡住。

试试这个:

            ROW_NUMBER() OVER (
                ORDER BY                    
                    CASE WHEN @orderby = 0 AND @orderdir = 1 THEN ne.[time] END DESC,    
                    CASE WHEN @orderby = 0 AND @orderdir = 2 THEN ne.[time] END ASC,    
                    CASE WHEN @orderby = 1 AND @orderdir = 1 THEN ne.lastedit END DESC,
                    CASE WHEN @orderby = 1 AND @orderdir = 2 THEN ne.lastedit END ASC,
                    CASE WHEN @orderby = 2 AND @orderdir = 1 THEN ne.title END ASC
                    CASE WHEN @orderby = 2 AND @orderdir = 2 THEN ne.title END DESC
                )
于 2012-04-04T21:55:37.627 回答
4

这对我来说很好 - (在哪里,顺序,方向,偏移获取)

       -- parameters

        @orderColumn  int ,
        @orderDir  varchar(20),
        @start  int ,
        @limit  int


        select * from items
        WHERE        (items.status = 1) 
        order by 

        CASE WHEN @orderColumn = 0 AND @orderdir = 'desc' THEN items.[category] END DESC,    
        CASE WHEN @orderColumn = 0 AND @orderdir = 'asc' THEN items.[category] END ASC,    
        CASE WHEN @orderColumn = 1 AND @orderdir = 'desc' THEN items.[category] END DESC,
        CASE WHEN @orderColumn = 1 AND @orderdir = 'asc' THEN items.[category] END ASC,
        CASE WHEN @orderColumn = 2 AND @orderdir = 'desc' THEN items.[category] END DESC,
        CASE WHEN @orderColumn = 2 AND @orderdir = 'asc' THEN items.[category] END ASC

        OFFSET @start ROWS FETCH NEXT @limit ROWS ONLY 
于 2015-12-30T08:33:15.623 回答