【问题标题】:Inline Conditional Statement in Stored Procedure存储过程中的内联条件语句
【发布时间】:2010-04-07 05:00:40
【问题描述】:

这是我代码中内联查询的伪代码:

select columnOne
from myTable
where columnOne = '#variableOne#'
  if len(variableTwo) gt 0
      and columnTwo = '#variableTwo#'
  end

我想将其移入存储过程,但无法正确构建查询。我认为它会像

select columnOne
from myTable
where columnOne = @variableOne
  CASE
    WHEN len(@variableTwo) <> 0 THEN and columnTwo = @variableTwo
  END

这给了我一个语法错误。

谁能告诉我我做错了什么。

另外,我想只保留一个查询,而不是只有一个 if 语句。另外,我不想在存储过程中构建sql并在其上运行Exec()

【问题讨论】:

标签: sql-server-2005 tsql stored-procedures conditional case


【解决方案1】:

切换你的逻辑,你就能得到你想要的结果。

select columnOne
from myTable
where columnOne = @variableOne
and (len(@variableTwo) = 0 or columnTwo = @variableTwo)

【讨论】:

  • 这解决了我的一个问题。另一个是 order by 子句。我想说类似 order by CASE WHEN @variableThree = 'somevalue' THEN columnThree, END columnFour 有什么帮助吗?
  • 如果两列是相同的数据类型,你可以做一个 case 语句:ORDER BY CASE WHEN @variableThree='somevalue' THEN columnThree ELSE columnFour END。如果不是,您可以进行某种类型的转换,但如果您将 int 转换为 varchars,那么它将无法正确排序('1000' 的排序将低于 '999')。在这一点上,我会使用 IF 语句。 :-)
猜你喜欢
  • 1970-01-01
  • 2012-08-17
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 2010-12-21
  • 2015-01-29
相关资源
最近更新 更多