DESC和ASC作为存储过程中的参数

问题描述

行号不会在每一行上求值,但是case语句是有效的,因此无论大小写如何,您都被行号所困扰。

尝试以下方法

            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
                )

解决方法

我使用以下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作为该参数完全相同的结果。