简体   繁体   中英

Oracle - using optional variable on dynamic SQL statement

I've got the following scenario:

declare
  dinamicsql    varchar2(500);
  whereclause   varchar2(500);
  returnval     numeric;
  dinamicAuxVal numeric;
begin
  dinamicAuxVal := 2;
  dinamicsql    := 'select dummy from dual ' || whereclause;
  execute immediate dinamicsql
   into returnval
   using dinamicAuxVal;

  dbms_output.put_line(returnval);
end;

The 'whereclause' variable is a dynamic where clause that may not use the dinamicAuxVal variable. When the variable is not used in 'whereclause' I get the exception 'Bind Variable Error - ORA-01006'.

I understand why this happens, but is there any way around?

whereclause is not initialized! Try with:

whereclause := <whatever you want>;
dinamicsql    := 'select dummy from dual ' || whereclause;

See also: https://www.techonthenet.com/oracle/errors/ora01006.php

Use if then clause to initialize the variable dinamically. For example:

whereclause := '';
IF <you need a where clause> THEN
    whereclause := 'where xyz ... ';
END IF;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM