Skip to Main Content

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, jack.

Asked: April 28, 2022 - 4:29 pm UTC

Last updated: May 03, 2022 - 3:22 am UTC

Version: 19C

Viewed 1000+ times

You Asked

Hi Tom,

I'd like to create a dynamic Sql with parameters so it fits "Execute immediate select ... into ... using p1, p2, ...". Depending on the inputs, the number of parameters in the USING clause could change (let's say I have 10 combinations). What's the best practice to accomplish this?

Many thanks,
Jack

and Connor said...

If the columns are you select is fixed, then execute immediate will be fine, eg

l_sql := 'select c1,c2,c3 from mytable where 1=1 ';

l_sql := 
  l_sql || 
    case 
      when bind1 is not null then 
        ' and mycol = :bind1 '
      else 
        ' and :bind1 is null'
    end;
    
l_sql := 
  l_sql || 
    case 
      when bind2 is not null then 
        ' and mycol2 = :bind2 '
      else 
        ' and :bind2 is null'
    end;
...
...



That way, the number of binds is fixed , so you just do

execute immediate l_sql using bind1,bind2,bind3,.....bind10;

even if some of the binds are null.

If you want more flexibility, ie, the columns you select is variable etc, then its time for DBMS_SQL

https://asktom.oracle.com/pls/apex/asktom.search?tag=execute-immediate-dont-know-how-many-input-variables

Is this answer out of date? If it is, please let us know via a Comment

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library