动态PL / SQL查询,如何忽略null参数?

时间:2011-02-08 11:06:35

标签: sql oracle dynamic plsql

我有一个带有多个参数的PL / SQL过程。当webapp调用该过程时,如果它没有使用某个参数,则它传递为null,即

procedure test (param1 in varchar2, param2 in varchar2, param3 in varchar2, cursor out sys_refcursor)
...
end procedure test;

我想创建一个SQL查询,只有在参数不为null时才在WHERE子句中包含给定的参数。有没有办法以优雅的方式实现这一点,除了在字符串中构建SQL查询然后打开该字符串的光标,就像这样

vSQL := 'SELECT * from TABLE WHERE something = something_else';
if param1 IS NOT NULL
    vSQL := vSQL || 'AND some_param = ' || param1;

3 个答案:

答案 0 :(得分:1)

我已经回答了类似的问题on dba.stackexchange.com

答案 1 :(得分:1)

您可以将其全部编码为单个选择

SELECT * from TABLE WHERE something = something_else
AND ((param1 IS NOT NULL AND some_param = param1) OR 1)

答案 2 :(得分:0)

创建一个测试表:

create table testtab
(
name_first varchar2(50),
name_last varchar2(50),
name_middle varchar2(50)
);

insert into testtab values ('Joe', 'Jones', 'A');
insert into testtab values ('Joe', 'Smith', 'A');
insert into testtab values ('Steve', 'Jones', 'B');
insert into testtab values ('Axl', 'Rose', 'C');
insert into testtab values ('Phil', 'McCracken', 'D');
commit;

创建您的程序:

CREATE OR REPLACE procedure ECDATA.get_testtab_rows
(i_name_first in varchar2 default null,
i_name_last in varchar2 default null,
i_name_middle in varchar2 default null,
o_cursor out sys_refcursor
) as

    v_result_cur    sys_refcursor;

begin

    open v_result_cur for
        select * from testtab
        where name_first like nvl(i_name_first, '%')
        and name_last like nvl(i_name_last, '%')
        and name_middle like nvl(i_name_middle, '%')
    ;

    o_cursor := v_result_cur;

end;
/

然后这样称呼:

declare

    v_cur sys_refcursor;
    testtab_rec testtab%rowtype;

begin

    get_testtab_rows(i_name_last=>'Jones', o_cursor=>v_cur);
    loop

        fetch v_cur into testtab_rec;
        exit when v_cur%notfound;
        dbms_output.put_line(testtab_rec.name_first || ' ' || testtab_rec.name_middle || ' ' || testtab_rec.name_last);

    end loop;

exception
    when others then raise;
end;