如何从变量设置ASC / DESC顺序

时间:2013-12-18 09:26:47

标签: sql-server sql-server-2008 tsql

当我尝试按列索引(数值)使用Order By时,我遇到了问题。

本作品:

  @OrderBy = 1

  SELECT Col1,Col2 FROM Table ORDER BY @OrderBy ASC

这不起作用:

  @OrderBy = 1
  @Direction = 'ASC'

  SELECT Col1,Col2 FROM Table ORDER BY @OrderBy @Direction

按数字列号排序时,如何按变量的方向使用订单?

2 个答案:

答案 0 :(得分:3)

ORDER BY
  case when @Direction = 'ASC' THEN field END ASC ,
  case when @Direction = 'DESC' THEN field END DESC

答案 1 :(得分:0)

试试这个:

ORDER BY @OrderBy CASE @Direction WHEN 'ASC' THEN @OrderBy ELSE -@OrderBy END ASC