Parameters 可选参数作为游标中的条件(PL/SQL)

Parameters 可选参数作为游标中的条件(PL/SQL),parameters,plsql,cursor,Parameters,Plsql,Cursor,我有一个采用可选参数的函数/过程。如果提供,我需要使用参数作为游标的条件。如果没有提供,那么我不想要那个条件 下面是我提出的一个非常简化的版本: 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

我有一个采用可选参数的函数/过程。如果提供,我需要使用参数作为游标的条件。如果没有提供,那么我不想要那个条件

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

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;

如果没有提供参数,是否有一种方法可以让光标移动一次并指示要忽略哪些条件?

您可以让查询一次性处理所有场景,例如:

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

也可以使用nvl,它稍微短一点:

select col1, col2
from table_a
where col1 = nvl(p_parm1,col1)
and col2 = nvl(p_parm2,col2);
那么您要做的是:当p_parm1为null时,将其等于条件的列(在比较col1和p_parm1的情况下)


如果需要,p_parm2也一样。

我试试这个。我建议使用COALESCE函数,并在未提供时将变量设置为通配符,ei:v_variable1:=COALESCE(p_parm1,“%”);/*然后在where子句中*/where表达式,如v_variable1;但这会导致大量的表扫描,需要很长时间才能返回。我担心的是,接受所有场景的单个查询将具有类似的性能,但我会尝试。非常感谢。我显然需要15个声望来投票,但这种方法确实有效。我认为我的效率受到了巨大的影响,因为我选择了一个视图,但也许我可以解决这个问题。这个概念起作用了,让我开始寻找解决方案。多谢各位!
create or replace procedure check_data
  (p_parm1 in varchar2 default null,
   p_parm2 in number default null)
is
begin
    select col1, col2
    from table_a
    where (CASE
      WHEN (p_parm1 IS NOT NULL AND col1 = p_parm1) THEN (1)
      WHEN (p_parm1 IS NULL) THEN (1)
      ELSE 0
    END) = 1