Использование CASE внутри условия where - PullRequest
1 голос
/ 29 апреля 2019

Я пытаюсь включить условие CASE в предложение where, поскольку мы не можем использовать условие if.У меня есть это, если код условия со мной.Я хочу включить его в пункт где.Для этой цели я использую 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;

Ответы [ 2 ]

2 голосов
/ 29 апреля 2019

«Условие 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 голосов
/ 29 апреля 2019

Дело не в том, как работает. Вы не можете вернуть условие, только значение

Попробуйте ИЛИ

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)
    )
...