【问题标题】:Use of CASE inside where clause在 where 子句中使用 CASE
【发布时间】:2019-04-29 08:14:00
【问题描述】:

我正在尝试将 CASE 条件合并到 where 子句中,因为我们不能使用 if 条件。我有这个 if 条件代码。我想将它包含在 where 子句中。为此,我正在使用 CASE,但它似乎不起作用,出现以下错误:

ORA-00905: missing keyword

我尝试过类似的 CASE 条件:

AND (CASE
        WHEN p_trx_date_low Is Null and p_trx_date_high Is Null
        Then a.trx_date = a.trx_date
        WHEN p_trx_date_low Is Not Null and p_trx_date_high Is Null
        Then a.trx_date >= p_trx_date_low
        WHEN p_trx_date_low Is Null and p_trx_date_high Is Not Null
        Then a.trx_date <= p_trx_date_high
        WHEN p_trx_date_low Is Not Null and p_trx_date_high Is Not Null 
        Then a.trx_date between p_trx_date_low and p_trx_date_high
      End CASE)

代替下面的if条件:

If :p_trx_date_low Is Null and :p_trx_date_high Is Null Then
  :p_trx_date_clause := ' and a.trx_date = a.trx_date ';
ElsIf :p_trx_date_low Is Not Null and :p_trx_date_high Is Null Then
  :p_trx_date_clause := ' and a.trx_date >= :p_trx_date_low ';
ElsIf :p_trx_date_low Is Null and :p_trx_date_high Is Not Null Then
  :p_trx_date_clause := ' and a.trx_date <= :p_trx_date_high ';
ElsIf :p_trx_date_low Is Not Null and :p_trx_date_high Is Not Null Then
  :p_trx_date_clause := ' and a.trx_date between :p_trx_date_low and :p_trx_date_high ';
End If;

【问题讨论】:

  • 在 If 条件中您将比较条件作为字符串传递。
  • 一般来说,在WHERE 子句(或ON 子句)中最好使用AND/OR 结构而不是case

标签: sql oracle case where-clause


【解决方案1】:

“如果条件”可以直译为:

AND (:p_trx_date_low IS     NULL AND :p_trx_date_high IS     NULL AND a.trx_date = a.trx_date)
OR  (:p_trx_date_low IS NOT NULL AND :p_trx_date_high IS     NULL AND a.trx_date >= :p_trx_date_low)
OR  (:p_trx_date_low IS     NULL AND :p_trx_date_high IS NOT NULL AND a.trx_date <= :p_trx_date_high)
OR  (:p_trx_date_low IS NOT NULL AND :p_trx_date_high IS NOT NULL AND a.trx_date BETWEEN :p_trx_date_low AND :p_trx_date_high)

并且可以简化为:

(:p_trx_date_low  IS NULL OR a.trx_date >= :p_trx_date_low) AND
(:p_trx_date_high IS NULL OR a.trx_date <= :p_trx_date_high)

【讨论】:

    【解决方案2】:

    这不是案例的工作方式。不能返回条件,只能返回值

    试试或

    AND (
        (p_trx_date_low Is Null and p_trx_date_high Is Null and a.trx_date = a.trx_date)
        OR
        (p_trx_date_low Is Not Null and p_trx_date_high Is Null and a.trx_date >= p_trx_date_low)
        OR
        (p_trx_date_low Is Null and p_trx_date_high Is Not Null and a.trx_date <= p_trx_date_high)
        OR
        (p_trx_date_low Is Not Null and p_trx_date_high Is Not Null and a.trx_date between p_trx_date_low and p_trx_date_high)
        )
    

    【讨论】:

      猜你喜欢
      • 2016-03-24
      • 1970-01-01
      • 2021-03-14
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 2017-01-27
      • 1970-01-01
      相关资源
      最近更新 更多