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

时间:2012-04-04 21:49:33

标签: sql sql-server-2008 tsql

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

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

2 个答案:

答案 0 :(得分:17)

行数不会在每一行上进行评估,但是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
                )

答案 1 :(得分:1)

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

       -- 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