在where子句中使用CASE

问题描述 投票:1回答:2

我试图在where子句中包含CASE条件,因为我们无法使用条件。如果条件代码与我,我有这个。我想把它包含在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 :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;
sql oracle case where-clause
2个回答
2
投票

“if条件”可以从字面上翻译成这样:

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)

0
投票

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

尝试OR

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)
    )
© www.soinside.com 2019 - 2024. All rights reserved.