删除表如果 Oracle 中存在(IF EXIST)

Abd*_*him 4 sql oracle sqlplus

我正在使用 Oracle 12c,并且我不想在删除表“CONTINENT”时出现错误(以防它不存在)。

我做了这个

set echo on
set serveroutput on
alter session set current_schema=WORK_ODI;
set verify off
set pause off

begin
  execute immediate 'drop table continent';
  exception when others then null;
end;
Run Code Online (Sandbox Code Playgroud)

这个脚本很适合我。我也使用这个脚本:

declare
   c int;
begin
   select count(*) into c from user_tables where table_name = upper('continent');
   if c = 1 then
      execute immediate 'drop table continent';
   end if;
end;
Run Code Online (Sandbox Code Playgroud)

这两个脚本都运行良好,但我的老板想要类似的东西IF EXIT。任何人都可以帮助我。在这种情况下如何使用 IF EXIT ?

Mar*_*ber 5

你可以做两件事

  • 定义您想要忽略的异常(此处为ORA-00942)

  • 添加一个未记录的(且未实现的)提示 /*+ IF EXISTS */ 这将使您的管理层满意。

declare
  table_does_not_exist exception;
  PRAGMA EXCEPTION_INIT(table_does_not_exist, -942);
begin
  execute immediate 'drop table continent /*+ IF EXISTS */';
  exception when table_does_not_exist then 
        DBMS_OUTPUT.PUT_LINE('Ignoring table or view does not exist')
   ;
end;
/
Run Code Online (Sandbox Code Playgroud)

附加说明:使用

 exception when others then null;
Run Code Online (Sandbox Code Playgroud)

可能很危险,例如,当表未DROPPED时,您还会忽略诸如表空间离线之类的错误。