Dynamic sql中的Where子句

时间:2017-06-19 19:38:26

标签: oracle oracle12c

我正在尝试获取bank_id为01的所有表。 我写了以下块

DECLARE

 cursor cBankId is
     select owner||'.'||table_name from all_tab_columns where column_name = 'BANK_ID';
        v_table     all_tab_columns.table_name%TYPE;
        vcount varchar2(50);

BEGIN

     open cBankId;
    loop
        fetch cBankId into v_table;
        exit when cBankId%notfound;

execute immediate 'select count(*) from ' || v_table into vcount || ' where bank_id  = 01';


IF vcount > 0 THEN
    DBMS_OUTPUT.PUT_LINE (v_table);
END IF;

end loop;
    close cBankId;

END;

我想知道如何在execute immediate语句中放置where子句。 我收到了错误 ORA-06550:第15行,第67栏: PLS-00103:遇到符号" |"期待以下之一:

。 (,%;使用

返回返回

2 个答案:

答案 0 :(得分:0)

您只需要更改编写查询部分的顺序。 使用动态SQL时,您需要以下内容:

SQL> declare
  2      v_table varchar2(30);
  3      vCount  number;
  4  begin
  5      v_table := 'dual';
  6      execute immediate 'select count(*) from ' || v_table  || ' where 1=1' into vcount;
  7      --
  8      dbms_output.put_line('vCount: ' || vCount);
  9  end;
 10
 11  /
vCount: 1

PL/SQL procedure successfully completed.

即:execute immediate 'select ... from ... where ...' INTO ...;

答案 1 :(得分:-1)

您不能动态地为表名使用变量,而是使用:

DECLARE

cursor cBankId is
 select owner||'.'||table_name from all_tab_columns where column_name = 'BANK_ID';
    v_table     all_tab_columns.table_name%TYPE;
    vcount varchar2(50);
    v_sql varchar2(1000);


BEGIN

 open cBankId;
loop
    fetch cBankId into v_table;
    exit when cBankId%notfound;

v_sql := 'select count(*) from ' || v_table || ' into vcount where bank_id  = 01';   

execute immediate v_sql;

IF vcount > 0 THEN
    DBMS_OUTPUT.PUT_LINE (v_table);
END IF;

end loop;
    close cBankId;

END;