Drop table from oracle database if table exist in sql statement [duplicate]

本秂侑毒 提交于 2019-12-02 05:31:23

问题


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");


回答1:


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.

Hope that helps.




回答2:


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.




回答3:


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




回答4:


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;




回答5:


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.



来源:https://stackoverflow.com/questions/22875300/drop-table-from-oracle-database-if-table-exist-in-sql-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!