您好我有以下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中处理此问题的任何线索?
感谢。
答案 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
。