Oracle/Drop if exists

From YavInWiki
Jump to navigation Jump to search

There is no special syntax for this case, so we have to use some workarounds.

The following PL/SQL statement will try to drop a table and ignore the exception, if one occurs:

Begin
  execute immediate 'drop table my_table';
  Exception when others then null;
End;
/

This statement checks if an object with this name exists and drops it, if it exists:

DECLARE exists PLS_INTEGER;
BEGIN
  select count(*) into exists from user_tables where table_name = 'my_table';
  if exists = 1 then
    execute immediate 'drop table my_table';
  end if;
END;
/

The last statement will only work for tables, it has to be modified to work for functions, views, procedures etc. since we make a select on user_tables. The first example should work for all object types.