2013-02-19 47 views
1

嗨選擇,我有以下SQL存儲過程查詢如何下令列的#在SQL查詢

@colindex int 

SELECT 
    di.folio, 
    di.name, 
    di.region, 
    di.amount 
FROM datainfo di 
WHERE di.isactive = 1 
ORDER BY [email protected] 'where colindex is the index of the column returned 

例子:

如果@colindex = 1則列,我想順序是「folio」列。

如果@colindex = 4,那麼我想要排序的列是「amount」列。

關於如何在SQL中處理此問題的任何線索?

謝謝。

回答

2
@colindex int 

SELECT 
    di.folio, 
    di.name, 
    di.region, 
    di.amount 
FROM datainfo di 
WHERE di.isactive = 1 
ORDER BY case @colindex when 1 then di.folio when 4 then di.amount end 
+0

也可能有@ordertype(asc或desc)並將其添加到查詢中? – VAAA 2013-02-19 17:42:49

+0

@VAAA ....是的:-) – 2013-02-19 17:51:20

+0

關於如何做到這一點的任何線索?非常感謝你的幫助! – VAAA 2013-02-19 17:53:24

3
order by case @colindex when 1 then folio when 2 then ... end 
+0

+1你剛纔打我吧:) – twoleggedhorse 2013-02-19 17:26:22

+0

按秒打我,你這該死的回車符:P – bendataclear 2013-02-19 17:27:48

1

不知道這將是非常快的,但你可以添加:

ORDER BY CASE @colindex 
      WHEN 1 THEN [MyColumn1] 
      WHEN 2 THEN [MyColumn2] 
      WHEN 3 THEN [MyColumn3] 
      WHEN 4 THEN [MyColumn4] 
     END 

要添加遞增/遞減:

ORDER BY CASE @sortorder 
    WHEN 'ASC' THEN 
     CASE @colindex 
      WHEN 1 THEN [MyColumn1] 
      WHEN 2 THEN [MyColumn2] 
      WHEN 3 THEN [MyColumn3] 
      WHEN 4 THEN [MyColumn4] 
     END 
    END, 
    CASE @sortorder 
     WHEN 'DES' THEN 
     CASE @colindex 
      WHEN 1 THEN [MyColumn1] 
      WHEN 2 THEN [MyColumn2] 
      WHEN 3 THEN [MyColumn3] 
      WHEN 4 THEN [MyColumn4] 
     END 
    END DESC 

要解釋,這兩個命令都將適用,但當@sortorder變量爲'ASC'時,第一個將不斷地NULL

+0

爲什麼downvoted?還有另外3個人在這個人後面提出了這個相同的事情 – 2013-02-19 17:27:13

+0

@АртёмЦарионов首先,這裏只有兩個其他答案,其次,bwperrin首先回答了這個問題。如果你會變得不開朗,那就直接告訴你事實。 – twoleggedhorse 2013-02-19 17:29:54

+0

也可能有@ordertype(asc或desc)並將其添加到查詢中? - – VAAA 2013-02-19 17:49:20