I am getting error when using case with where clause ORA-00905: missing keyword on between
SELECT 1 FROM TABLE T, TABLEAAA O
WHERE T.ID = O.ID
AND (CASE WHEN :P_PIM_DATE1 IS NOT NULL AND :P_PIM_DATE2 IS NOT NULL) THEN T.F_DATE BETWEEN :P_PIM_DATE1 AND :P_PIM_DATE2 END)
1
Query you posted doesn’t make much sense. You tried to say what to do when parameters (preceded by a colon sign; these are some kind of parameters, aren’t they?) aren’t null. But, you didn’t say what to do when they are null.
Perhaps you’d rather include the NVL
function which would then satisfy both conditions; something like this:
select 1
from tablea t join tableaaa o on o.id = t.id
where t.f_date between nvl(:P_PIM_DATE , trunc(sysdate))
and nvl(:P_PIM_DATE2, trunc(sysdate + 1));
which returns rows whose f_date
is either between parameters’ values, or “today” and “tomorrow”. That’s just an illustration, I don’t know what you really want to do.
(Also, maybe you noticed, I switched to explicit join
. Leave where
clause to conditions which filter data).
2
You are putting the case when
part into parantheses and follow up with a then
outside the parantheses. Try it this way:
SELECT 1 FROM TABLE T, TABLEAAA O
WHERE T.ID = O.ID
AND CASE WHEN (:P_PIM_DATE1 IS NOT NULL AND :P_PIM_DATE2 IS NOT NULL) THEN T.F_DATE BETWEEN :P_PIM_DATE1 AND :P_PIM_DATE2 END
Also, you do not have an else
, so your criteria defaults to null if your T.F_DATE
is not in the range.
2
A CASE
expression returns an scalar expression and not a comparison between expressions.
Use OR
:
SELECT 1
FROM TABLE T
INNER JOIN TABLEAAA O
ON T.ID = O.ID
WHERE :P_PIM_DATE1 IS NULL
OR :P_PIM_DATE2 IS NULL
OR T.F_DATE BETWEEN :P_PIM_DATE1 AND :P_PIM_DATE2;
or, using legacy comma joins:
SELECT 1
FROM TABLE T,
TABLEAAA O
WHERE T.ID = O.ID
AND ( :P_PIM_DATE1 IS NULL
OR :P_PIM_DATE2 IS NULL
OR T.F_DATE BETWEEN :P_PIM_DATE1 AND :P_PIM_DATE2
);