0

oracle: drop table if exists pl/sql not working using exception. e.g.,

SQL> SET SERVEROUTPUT ON
SQL> BEGIN 
SQL>   EXECUTE IMMEDIATE 'DROP TABLE Foo'; 
SQL>  EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(sqlerrm); 
SQL> END;
SQL> /

The Foo table is not dropped.

create table Foo (id number(20,0), name varchar(20), 
    primary key(id));
create table Bar (id number(20,0), name varchar(20), 
    primary key(id),
    constraint FK1 foreign key (id) references Foo (id));

There is a FK constraint.

SET CONSTRAINTS ALL DEFERRED;
BEGIN EXECUTE IMMEDIATE 'DROP TABLE Foo'; EXCEPTION WHEN OTHERS THEN NULL; END;
/
SET CONSTRAINTS ALL IMMEDIATE;

The table Foo is not deleted.

eastwater
  • 4,624
  • 9
  • 49
  • 118

1 Answers1

0

How about this?

If table doesn't exist:

SQL> set serveroutput on;
SQL> select table_name from user_tables where upper(table_name) = 'FOO';

no rows selected

SQL> declare
  2    l_nex exception;
  3    pragma exception_init (l_nex, -942);
  4  begin
  5    execute immediate 'drop table foo';
  6  exception
  7    when l_nex then
  8      dbms_output.put_line('You can not drop a table that does not exist');
  9  end;
 10  /
You can not drop a table that does not exist

PL/SQL procedure successfully completed.

SQL>

If table exists:

SQL> create table foo (id number);

Table created.

SQL> declare
  2    l_nex exception;
  3    pragma exception_init (l_nex, -942);
  4  begin
  5    execute immediate 'drop table foo';
  6  exception
  7    when l_nex then
  8      dbms_output.put_line('You can not drop a table that does not exist');
  9  end;
 10  /

PL/SQL procedure successfully completed.

SQL> select table_name from user_tables where upper(table_name) = 'FOO';

no rows selected

SQL>
Littlefoot
  • 131,892
  • 15
  • 35
  • 57