问题
I have a requirement where in i'm supposed to take 3 dynamic values from the user and compare with the list of values present based on match of it I need to have conditions to be added to where clause using case statement.
select *
from MY_DBSOURCE
WHERE 1=1
And LP_WHERE_REP = (CASE When :LP = 'LIFESHEILD' AND :M = 'AP' AND :STATUS = 'Processed' THEN flag ='P' and Manual_FLAG = 'P' END)
AND DATA_SOURCE IN ('LIFESHIELD')
AND DATE_CLOSED >= '15-JUL-2019'
AND DATE_CLOSED <= '16-JUL-2019'
回答1:
CASE
can be used in WHERE
, but - syntax should be OK. Yours isn't.
Here's an example which shows how to do it (also, note that I used date literal for date_closed
; you compared it to strings.
select *
from my_dbsource
where 1=1
and lp_where_rep = case when :lp = 'LIFESHEILD' and :m = 'AP' and :status = 'Processed' then 'P'
when manual_flag = 'P' then 'X'
else 'Y'
end
and data_source in ('LIFESHIELD')
and date_closed >= date '2019-07-15'
and date_closed <= date '2019-07-16'
回答2:
If you want to use a case in WHERE
clause then you can use something like the following:
AND (CASE WHEN :LP = 'LIFESHEILD' AND :M = 'AP' AND :STATUS = 'Processed' THEN flag ELSE 'P' END) = 'P'
AND (CASE WHEN :LP = 'LIFESHEILD' AND :M = 'AP' AND :STATUS = 'Processed' THEN Manual_FLAG ELSE 'P' END) = 'P'
Cheers!!
来源:https://stackoverflow.com/questions/57040183/using-case-statement-compare-3-conditions-and-have-the-statements-executed