【问题标题】:How to set Order By ASC/DESC from a Variable [duplicate]如何从变量设置按 ASC/DESC 排序 [重复]
【发布时间】:2013-12-18 09:26:47
【问题描述】:

当我尝试按列索引(数值)使用 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

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

【问题讨论】:

  • 这是做什么的?如果不是字符串,则不能将 ASCDESC 存储在变量中。
  • 我不认为当 OR 动态查询 时可能有例外情况

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


【解决方案1】:
ORDER BY
  case when @Direction = 'ASC' THEN field END ASC ,
  case when @Direction = 'DESC' THEN field END DESC

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2019-08-13
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 2015-04-12
      相关资源
      最近更新 更多