如何使用FOR ORACLE将列值从FOR LOOP传递到查询中?

时间:2018-10-05 07:51:29

标签: oracle plsql

我正在尝试将For循环中的值传递给Select进入查询。但是它无法传递值。而是显示字符串本身。下面是我的相似查询。

DECLARE

filters  VARCHAR2(4000);

BEGIN

    FOR SRC IN (SELECT ABC , EFG , HIJ ,KLM FROM table_name WHERE rownum < 2)

    LOOP

    FILTERs := '';

    FOR con IN (SELECT DISTINCT cols.column_name AS COL FROM all_constraints cons, all_cons_columns cols
                WHERE cols.table_name = table_name
                AND cons.constraint_type = 'P'
                AND cons.constraint_name = cols.constraint_name
                AND cons.owner = OWNER_NAME)                
    LOOP

    select filters || con.col || ' = ''''''|| SRC.' ||con.col||'||'''''' AND ' INTO filters FROM dual;

    END LOOP;   

    dbms_output.put_line(Filters);

    END LOOP;
END;

我得到的输出是:

ABC = '''|| SRC.ABC||''' AND EFG = '''|| SRC.EFG||''' AND 

但是我期望的是:

ABC = '1234' AND EFG = '5678' AND

我该怎么做?

1 个答案:

答案 0 :(得分:2)

此代码块对我有用。您必须在这里使用动态SQL。

样本数据:

create table table_name(abc, efg, hij, klm) as (
    select '1234', '5678', 'PQR', 'XYZ' from dual union all
    select '1221', '8688', 'ABQ', 'ZAA' from dual 
    );
alter table table_name add constraint tn_pk primary key (abc, efg);

代码块:

declare
  v_flt varchar2(4000);
  v_val varchar2(1000);
  v_sql varchar2(4000);
begin
  for r in (select rowid rwd from table_name where rownum <= 2) loop
      v_flt := '';
      for con in (select column_name col
                    from all_constraints  cons
                    join all_cons_columns cols using (owner, table_name, constraint_name)
                    where owner = 'SCOTT' 
                      and table_name = 'TABLE_NAME' 
                      and constraint_type = 'P') 
      loop
        v_sql := 'select '||con.col||' from table_name where rowid = '''||r.rwd||'''' ;
        execute immediate v_sql into v_val;
        v_flt := v_flt ||con.col||' = '''||v_val||''' AND ';
      end loop;
      dbms_output.put_line(v_flt);
  end loop;
end;

结果:

ABC = '1221' AND EFG = '8688' AND 
ABC = '1234' AND EFG = '5678' AND