2012-04-04 57 views
9

我有以下用於分頁新聞文章列表的SP。您可能會猜到,@count是要返回的行數,@start是從中選擇行的索引(按內部查詢排序),@orderby指示要排序的列,@orderdir指示是排序一個方向還是排序其他。我的原始查詢是 here,之前我添加了@orderdir參數。DESC和ASC作爲存儲過程中的參數

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作爲該參數。

回答

15

行號在每一行都沒有被評估,但是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

燁是工作正是我想要的,它似乎很明顯現在你已經寫下來了。謝謝,必須等待標記爲答案。 – 2012-04-04 21:58:54

+0

沒有汗水。在row_number出來之前,我已經把這些東西抓了幾次。 – Gats 2012-04-07 02:46:56

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