如何将参数列表集成到LIKE子句中?

时间:2013-10-08 18:02:33

标签: parameters plsql oracle11g sql-like

当我列出parm_list_a中编写的代码时,此代码有效。但是,我想实施like,如parm_list_b所示。

如何使用parm_list_b

让此代码正常工作
set serveroutput on;
declare
parm_list_a varchar2(100) := 'ADAR,CADD';
parm_list_b varchar2(100) := 'A%,BE%'; 

cursor c_ok_counties 
is
with ok_counties as
(select 'ALFA' AS cty_code, 'Alfalfa' as cty_name from dual union all
 select 'ATOK' AS cty_code, 'Atoka'   as cty_name from dual union all
 select 'BEAV' AS cty_code, 'Beaver'  as cty_name from dual union all
 select 'BECK' AS cty_code, 'Beckahm' as cty_name from dual union all
 select 'BLAI' AS cty_code, 'Blaine'  as cty_name from dual union all
 select 'CADD' as cty_code, 'Caddo'   as cty_name from dual)
 select cty_code,
        cty_name
 from  ok_counties  
 where cty_code in 
      (select regexp_substr(
      parm_list_a,   -- Replace with parm_list_b
      '[^,]+',1,LEVEL)
      from dual
      connect by regexp_substr(
      parm_list_a  -- Replace with parm_list_b
      ,'[^,]+',1,LEVEL) is not null);

begin
         for county in c_ok_counties loop
         dbms_output.put_line(county.cty_code || ' ' ||county.cty_name);         
         end loop;
end;

期望的结果

   ALFA Alfalfa
   ATOK Atoka
   BEAV Beaver
   BECK Beckham

1 个答案:

答案 0 :(得分:1)

由于您必须在LIKE中多次使用IN, 您可以更好地编写代码:

set serveroutput on;
declare
parm_list_a varchar2(100) := 'ADAR,CADD';
parm_list_b varchar2(100) := 'A|BE'; 

cursor c_ok_counties 
is
with ok_counties as
(select 'ALFA' AS cty_code, 'Alfalfa' as cty_name from dual union all
 select 'ATOK' AS cty_code, 'Atoka'   as cty_name from dual union all
 select 'BEAV' AS cty_code, 'Beaver'  as cty_name from dual union all
 select 'BECK' AS cty_code, 'Beckahm' as cty_name from dual union all
 select 'BLAI' AS cty_code, 'Blaine'  as cty_name from dual union all
 select 'CADD' as cty_code, 'Caddo'   as cty_name from dual)
 select cty_code,
        cty_name
 FROM  OK_COUNTIES  
 where regexp_like(cty_code, '^('||parm_list_b||')');

begin
         for county in c_ok_counties loop
         dbms_output.put_line(county.cty_code || ' ' ||county.cty_name);         
         END LOOP;
end;