
SQL> conn sys/SysPassword1@//localhost:1521/freepdb1 as sysdbaConnected.SQL> create user testuser1 identified by testuser1;create user testuser1 identified by testuser1*ERROR at line 1:ORA-01920: user name 'TESTUSER1' conflicts with another user or role nameSQL>SQL> conn testuser1/testuser1@//localhost:1521/freepdb1Connected.SQL> create table t1 (id number);create table t1 (id number)*ERROR at line 1:ORA-00955: name is already used by an existing objectSQL>SQL> create sequence t1_seq;create sequence t1_seq*ERROR at line 1:ORA-00955: name is already used by an existing objectSQL>
SQL> drop table t3 purge;drop table t3 purge*ERROR at line 1:ORA-00942: table or view does not existSQL>
在实际工作中,我们往往希望在执行创建操作时,只有当对象不存在的情况下才进行创建;而在删除操作时,如果对象本身不存在,则不需要执行删除,也不希望因此而报错。这样一来,整个数据库操作就会更加智能和稳健,能够适应更多场景的需要。那么,有没有一种更为友好的方法来处理这种“有条件”的创建或删除操作呢?
幸运的是,从 Oracle 23ai 开始,DDL 语句中引入了全新的 IF [NOT] EXISTS 子句,这一特性正好解决了上述问题。利用这个子句,我们可以在执行创建操作前自动判断对象是否已经存在;如果存在则跳过创建步骤,而不会抛出任何错误。同理,在删除操作中加入 IF EXISTS 子句,则可以先检测对象是否存在,只有在对象确实存在的情况下才执行删除,从而避免因为删除一个不存在的对象而导致错误。
下面通过一些示例来说明这一新特性的具体应用。
首先看用户创建的场景:假设用户 TESTUSER1 已经存在,通过在 CREATE USER 语句中添加 IF NOT EXISTS 子句,系统就会判断该用户已经存在,因此不会重复创建,同时也不会返回任何错误信息,确保了操作的平稳进行。
同样地,在尝试删除一个不存在的用户(例如 TESTUSER3)时,通过使用 IF EXISTS 子句,Oracle 数据库会自动判断该用户是否存在。如果用户不存在,则直接跳过删除操作,而不会报错,从而使得整个过程更为友好和灵活。
SQL> conn sys/SysPassword1@//localhost:1521/freepdb1 as sysdbaConnected.SQL> create user if not exists testuser1 identified by testuser1;User created.SQL>SQL> drop user if exists testuser3 cascade;User dropped.SQL>
这一新语法不仅适用于用户对象,在创建或删除表、视图、序列、存储过程等各种数据库对象时,同样可以使用 IF [NOT] EXISTS 子句来屏蔽不必要的错误。
SQL> conn testuser1/testuser1@//localhost:1521/freepdb1Connected.SQL> create table if not exists t1 (id number);Table created.SQL>SQL> create sequence if not exists t1_seq;Sequence created.SQL>SQL> create view if not exists t1_v asselect * from t1;View created.SQL>SQL> create procedure if not exists p1 asbeginnull;end;/Procedure created.SQL>SQL> drop table if exists t3;Table dropped.SQL> drop sequence if exists t3_seq;Sequence dropped.SQL> drop view if exists t3_v;View dropped.SQL> drop procedure if exists p3;Procedure dropped.SQL>
SQL> create or replace view if not exists t1_v asselect * from t1;create or replace view if not exists t1_v as*ERROR at line 1:ORA-11541: REPLACE and IF NOT EXISTS cannot coexist in the same DDL statementSQL>
文章转载自山东Oracle用户组,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




