Question

I have to use an SQL statement to drop a table, it will crash if the table doesn't exist. Is it possible to use IF statement to drop the table s.executeUpdate("DROP TABLE employee");

Was it helpful?

Solution

Oracle does not support a construct like drop table if exists my_table, which is apparently legal syntax in MySQL (and possibly other RDBMSs).

In a .SQL script, where you're running DDL to DROP and/or CREATE various objects, the Oracle standard is to drop the object, and ignore the error in cases where the object does not exist. If you wish, you can write code to check if the object exists (see DBA_OBJECTS view) to only drop if it exists.

from the s.executeUpdate, I gather that you're doing this in Java? If it was me, I'd just do the drop and ignore any not exists error.

OTHER TIPS

assuming you have the right permissions, you can do something like the below

declare var_count int;
select count(*) INTO var_count
from all_tables where OWNER = [schema] and table_name = "EMPLOYEE";
if var_count > 0 then
begin
drop table employee;
end  

adapt accordingly if you are doing this in front-end code instead of a pl/sql procedure.

Traditionally in pl/sql you can specify an exception section in the block, and catch the exception if the table is not there to drop.

See Oracle errors handling

This will resolve your problem, when the table doesn't exist no error will be thrown.

BEGIN DROP TABLE employee; EXCEPTION WHEN OTHERS THEN NULL; END;

I would use the following code:

s.executeUpdate("DROP TABLE IF EXISTS employee")

But depending on your verions, you could also use this:

IF OBJECT_ID('dbo.employee', 'U') IS NOT NULL
DROP TABLE dbo.employee

Answer taken from: here, also this seems like it might be a duplicate of the same post? I would highly, highly recommend reading the SQL Documentation, and trying to do a bit more research before posting, but sense I see you are new, be sure to read the rules of posting here on StackOverFlow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top