如何按SQL查询中选择的列的顺序进行排序

时间:2013-02-19 17:23:40

标签: sql sql-server

您好我有以下SQL存储过程查询

@colindex int

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

示例:

如果@colindex = 1,那么我要订购的列是“folio”列。

如果@colindex = 4,那么我要订购的列是“amount”列。

有关如何在SQL中处理此问题的任何线索?

感谢。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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

答案 2 :(得分:1)

不确定这是否会非常快,但您可以添加:

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

添加asc / desc:

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

要解释一下,这两个订单都适用,但当NULL变量为'ASC'时,第一个订单将始终为@sortorder

相关问题