2011-05-06 59 views
4

內我有一個select語句下面的這結尾:多ORDER BY CASE

order by case @pcsort 
      when '' then compcode asc 
      else received asc, compcode asc 
     end 

基本上我需要它,如果@pcsort是 '由compcode',然後順序,否則爲了通過received並依次compcode

任何想法?

+0

「compcode」和「received」的數據類型是什麼? – 2011-05-06 09:08:12

回答

7

這將做你想做的假設數據類型相互兼容

order by 
    case @pcsort 
      when '' then compcode 
      else received 
    end ASC, 
    compcode ASC 

更一般地,你需要爲每個排序列一個CASE假設數據類型是兼容

order by 
    case @pcsort 
      when '' then compcode 
      else received 
    end ASC, 
    case @pcsort 
      --safe to sort on same column agaon , or use a constant 
      when '' then compcode or <constant of same type as compcode> 
      else compcode 
    end ASC 

如果數據類型是不兼容的,你需要更多的案例和大量的常量

order by 
case @pcsort 
     when '' then compcode 
     else <constant of same type as compcode> 
end ASC, 
    case @pcsort 
     when '' then <constant of same type as received> 
     else received 
end ASC, 
case @pcsort 
     when '' then <constant of same type as compcode> 
     else compcode 
end ASC