avoid 'IF' , if possible to check different condition in where clause
I have a query in which column used in where clause in changed depending on the parameter of the stored procedure:
select * from tableName where col2=someValue
above query runs if inputparameter is 'X' and if it is 'Y' then
select * from tableName where col2=someValue
I can write a if block checking for the condit开发者_如何转开发ion and then executing the respective query. but i am trying to combine these two query into one. Please help.
SELECT * from tableName
WHERE ( inputparameter = 'X' AND col1=someValue )
OR ( inputparameter = 'Y' AND col2=someValue )
;
WHERE :SomeValue = DECODE(:InputParameter, 'X', Col1, 'Y', Col2)
select * from tableName
where 1 = CASE
when inputparameter = 'X'
AND col1=someValue
THEN 1
when inputparameter = 'Y'
AND col2=someValue
THEN 1
ELSE 0
END
All solutions built around conditions in "where" part of query are working, but not optimal from performance point of view. Therefore, if tableName
is really big then better variant is building dynamic sql or implement this case as two separate query.
E.g.
create or replace procedure GetSomething(
inputParameter in varchar2,
someValue in varchar2
)
return sys_refcursor
as
cRet sys_refcursor;
begin
if(inputParam = 'X') then
open cRet for
select * from tableName where col1 = someValue
;
elsif(inputParam = 'Y') then
open cRet for
select * from tableName where col2 = someValue
;
else
raise_application_error(-20001,'Invalid value of inputParameter.');
end if;
end;
Of course, both columns must be indexed for good performance.
精彩评论