简体   繁体   中英

Confused about PL/SQL snippet with dynamic SQL

This snippet runs w/o errors unless I uncomment for loop, in which case I getting

Error report:
ORA-06550: line 12, column 41:
PL/SQL: ORA-00942: table or view does not exist

My question is why error occurs with for loop uncommented?

set serveroutput on
declare
  v_sql varchar2(2000);
  v_tmp number;
begin
  dbms_output.enable(null);
  v_sql := 'CREATE TABLE tmp_bank_codes (name varchar2(256), code varchar2(256))';
  dbms_output.put_line('Will do ' || v_sql);
  execute immediate v_sql;
  v_sql := 'INSERT INTO tmp_bank_codes (name, code) VALUES (''Bank of America'', ''BOANY (NY)'')';
  dbms_output.put_line('Will do ' || v_sql);
  execute immediate v_sql;
--for bank_code in (select name, code from tmp_bank_codes) loop
--  select 1 into v_tmp from dual;
--end loop;
execute immediate 'drop table tmp_bank_codes';
rollback;

end;
/

The error is because you use dynamic sql to create the table and the in the for loop you are using the table. While compiling the procedure, compiler doesnt know that you have created the table with dynamic sql

Here are your options:

  1. make the for loop also with Dynamic SQL
  2. change the dymamic sql to create the table to normal sql statement

I would prefer the second option, as the dynamic sql will not take the cached execution plans, thus slows down the query

For option 1 you could do this, replace your commented code part with the following

v_sql :='for bank_code in (select name, code from tmp_bank_codes) loop
        select 1 into v_tmp from dual;
        end loop';
execute immediate v_sql;

This is a parser error. tmp_bank_codes doesn't exist at compile-time.

First the engine tries to compile your anonymous script. In this first step tmp_bank_codes table does not exists.

A solution would be something like

execute immediate `select 1 from tmp_bank_codes where rownum = 1` into v_tmp;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM