Drop table if Exists in Oracle
In MySQL, we can easily drop table and check whether it is exist or not using this statement.
DROP TABLE IF EXISTS MyTable
In Oracle, you can’t do that.
Solution that I found is to create a procedure and execute it.
As for my reference and others (if any) here is the script to create that procedure.
create or replace procedure drop_table (tab_name in varchar2)
is
qry_string varchar2(4000);
cnt number;
begin
select count(1) into cnt from user_tables where lower(table_name) = lower(tab_name);
if cnt > 0 then
qry_string := 'DROP TABLE ' || tab_name;
begin
EXECUTE IMMEDIATE qry_string;
exception
when others then
dbms_output.put_line('Error occured while dropping ' || sqlerrm);
end;
else
dbms_output.put_line('TABLE ' || tab_name ||' does not exist');
end if;
end;
to drop your table, just execute this statement.
exec drop_table(‘MyTable’);
So, you can safely execute below statement without error if the table is not exist.
exec drop_table(‘MyTable’);
create table MyTable as select * from MyOtherTable;
