I'm writing some migration scripts for an Oracle database, and was hoping Oracle had something similar to MySQL's IF EXISTS
construct.
Specifically, whenever I want to drop a table in MySQL, I do something like
DROP TABLE IF EXISTS `table_name`;
This way, if the table doesn't exist, the DROP
doesn't produce an error, and the script can continue.
Does Oracle have a similar mechanism? I realize I could use the following query to check if a table exists or not
SELECT * FROM dba_tables where table_name = 'table_name';
but the syntax for tying that together with a DROP
is escaping me.
I prefer to specify the table and the schema owner.
Watch out for case sensitivity as well. (see "upper" clause below).
I threw a couple of different objects in to show that is can be used in places besides TABLEs.
.............
And a TABLE example:
I have been looking for the same but I ended up writing a procedure to help me out:
Hope this helps
Another method is to define an exception and then only catch that exception letting all others propagate.
// Doing this code, checks if the table exists and later it creates the table max. this simply works in single compilation
There is no 'DROP TABLE IF EXISTS' in oracle, you would have to do the select statement.
try this (i'm not up on oracle syntax, so if my variables are ify, please forgive me):
That's for checking whether a table in the current schema exists. For checking whether a given table already exists in a different schema, you'd have to use
all_tables
instead ofuser_tables
and add the conditionall_tables.owner = upper('schema_name')