2013-02-19 49 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