如果存在则添加约束(Oracle 11g,Postgres 8)

Fab*_*ani 4 sql oracle postgresql constraints exists

我很难制作一个脚本来从某些数据库中删除旧约束,然后用新引用创建新约束。

问题是数据库不相等。

例如:swpmnh数据库有fk_cmp_solicitaca_rh_contrat约束,但swpmcs数据库没有。因此,如果我执行该脚本,则会出现错误并且不会提交。

我知道 Postgres 9.xDROP CONSTRAINT IF EXISTS有这个功能,但是 Postgres 8.x 和 Oracle 11g 都没有这个功能。

我工作和学习SQL只有 3 个月,我知道这是一件简单的事情,但这对我来说是一个问题。

Ton*_*ews 7

这是您将得到的错误:

SQL> alter table my_tab drop constraint my_cons;
alter table my_tab drop constraint my_cons
                                   *
ERROR at line 1:
ORA-02443: Cannot drop constraint  - nonexistent constraint
Run Code Online (Sandbox Code Playgroud)

您可以在 PL/SQL 中捕获 ORA-02443 错误并忽略它(使用动态 SQL):

  1  declare
  2     e exception;
  3     pragma exception_init (e, -2443);
  4  begin
  5     execute immediate 'alter table my_tab drop constraint my_cons';
  6  exception
  7     when e then null;
  8* end;
SQL> /

PL/SQL procedure successfully completed.
Run Code Online (Sandbox Code Playgroud)

这有点冗长,因此您可以创建一个方便的过程:

create or replace procedure drop_constraint (p_table varchar2, p_constraint varchar2) is
   e exception;
   pragma exception_init (e, -2443);
begin
   execute immediate 'alter table ' || p_table || ' drop constraint '||p_constraint;
exception
   when e then null;
end;
Run Code Online (Sandbox Code Playgroud)

然后在需要时使用它:

execute drop_constraint ('my_tab', 'my_cons1');
execute drop_constraint ('my_tab', 'my_cons2');
execute drop_constraint ('another_tab', 'another_cons');
Run Code Online (Sandbox Code Playgroud)