Oracle - using optional variable on dynamic SQL statement

Viewed 79

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?

1 Answers

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;
Related