2014-02-28 27 views
0

我有一个采用可选参数的函数/过程。如果提供,我需要使用参数作为游标的条件。如果没有提供,那么我不希望这种情况。可选参数作为游标中的条件(PL/SQL)

下面是一个非常简化的版本是我想出来的:

create or replace procedure check_data 
    (p_parm1 in varchar2 default null, 
    p_parm2 in number default null) 
is 
begin 
    if (p_parm1 is null && p_parm2 is null) then 
    for rec in (select col_1, col_2 
     from table_a) 
    loop 
     /*Statements, use rec.col_1 and rec.col_2 */ 
    end loop; 
    elsif (p_parm1 is null) then 
    for rec in (select col_1, col_2 
       from table_a 
       where /*condition using p_parm2 */) 
    loop 
     /*Statements, use rec.col_1 and rec.col_2 */ 
    end loop; 
    elsif (p_parm2 is null) then 
    for rec in (select col_1, col_2 
       from table_a 
       where /*condition using p_parm1 */) 
    loop 
     /*Statements, use rec.col_1 and rec.col_2 */ 
    end loop; 
    else 
    for rec in (select col_1, col_2 
       from table_a 
       where /*condition using p_parm1 */ 
        and /*condition using p_parm2 */) 
    loop 
     /*Statements, use rec.col_1 and rec.col_2 */ 
    end loop; 
    end if; 
end; 

有没有办法让光标一次,表示如果不提供参数,忽略哪些条件?

回答

0

你可以让查询照顾所有场景中一气呵成,如:

select col_1, col_2 
from table_a 
where (p_parm1 IS NULL OR (p_parm1 = ...)) 
AND (p_parm2 IS NULL OR (p_parm2 = ...)); 
+0

我会试试这个。我建议使用COALESCE函数,并在未提供时将变量设置为通配符,即: v_variable1:= COALESCE(p_parm1,'%'); /*然后在where子句*/ 其中表达式LIKE v_variable1; 但这会导致需要太长时间才能返回的大规模表扫描。我的担心是,采取所有场景的单个查询将具有类似的性能,但我会尝试。 谢谢! – RuinExplorer

0

也有可能是使用NVL,这是一个有点短:

select col1, col2 
from table_a 
where col1 = nvl(p_parm1,col1) 
and col2 = nvl(p_parm2,col2); 

你这样做是什么:当p_parm1为空时,您将它等于条件的列(在将col1与p_parm1进行比较的情况下)。

+0

我显然需要15点声望投票,但这种方法确实有效。我认为我的效率受到了很大的打击,因为我选择了一种观点,但也许我可以解决这个问题。这个概念起作用,让我开始了解决方案。非常感谢! – RuinExplorer