Declaration of multiple values in Oracle BIND Variables

后端 未结 6 1979
庸人自扰
庸人自扰 2021-01-14 11:49

I am trying to pass multiple values about 3000 values, to a BIND variable in Oracle SQL PLUS command prompt like..

SELECT JOB
  FROM EMP 
 WHERE JOB IN :JOB          


        
6条回答
  •  半阙折子戏
    2021-01-14 12:04

    One way to do it in 10g and up is with subquery factoring.

    Assume :JOB is a comma-separated list of values. The following would work:

    with job_list as
    (select trim(substr(job_list,
                        instr(job_list, ',', 1, level) + 1,
                        instr(job_list, ',', 1, level + 1)
                          - instr (job_list, ',', 1, level) - 1
                       )
                ) as job
      from (select 
                   -- this is so it parses right
                   ','|| :JOB ||',' job_list
             from dual)
    connect by level <= length(:JOB)
                         - length (replace (:JOB, ',', '') ) + 1
    )
    select * from emp
     where job in (select * from job_list);
    

    It's a bit ugly to read, yes, but it works, and Oracle's clever enough to do the parsing of the list of values once, not once per row, which is what you end up with otherwise. What it does under the covers is build a temporary table of the parsed values, which it then can join to the base table.

    (I didn't come up with this on my own - original credit goes to an asktom question.)


    :JOB is a bind variable which must be declared and populated before it can be used. The statements below demonstrate how to do that with SQL*Plus.

    SQL> variable JOB varchar2(4000);
    
    SQL> exec :JOB := '10, 20';
    

提交回复
热议问题