Unlike MySQL, Oracle database has no direct IF EXISTS
syntax for table operations. However, we can achieve similar functionality through the following methods.
The most efficient way is to catch the "table does not exist" exception:
<code class="language-sql">BEGIN EXECUTE IMMEDIATE 'DROP TABLE ' || table_name; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -942 THEN RAISE; END IF; END;</code>
This method avoids the need to check whether the table exists twice like other methods.
IF EXISTS
Syntax (Oracle 23c and above) Starting with Oracle version 23c, all DROP
DDL operations support the simpler IF EXISTS
syntax:
<code class="language-sql">BEGIN EXECUTE IMMEDIATE 'DROP TABLE IF EXISTS ' || table_name; END;</code>
Similar exception handling blocks can be used for other Oracle object types:
<code class="language-sql">BEGIN EXECUTE IMMEDIATE 'DROP SEQUENCE ' || sequence_name; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -2289 THEN RAISE; END IF; END;</code>
<code class="language-sql">BEGIN EXECUTE IMMEDIATE 'DROP VIEW ' || view_name; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -942 THEN RAISE; END IF; END;</code>
<code class="language-sql">BEGIN EXECUTE IMMEDIATE 'DROP TRIGGER ' || trigger_name; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -4080 THEN RAISE; END IF; END;</code>
<code class="language-sql">BEGIN EXECUTE IMMEDIATE 'DROP INDEX ' || index_name; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -1418 THEN RAISE; END IF; END;</code>
<code class="language-sql">BEGIN EXECUTE IMMEDIATE 'ALTER TABLE ' || table_name || ' DROP COLUMN ' || column_name; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -904 AND SQLCODE != -942 THEN RAISE; END IF; END;</code>
The above is the detailed content of How to Check for Table Existence and Perform Conditional DDL Operations in Oracle?. For more information, please follow other related articles on the PHP Chinese website!