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

时间:2014-05-28 14:26:07

标签: sql oracle postgresql constraints exists

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

问题是数据库不相等。

例如:swpmnh数据库具有fk_cmp_solicitaca_rh_contrat约束,但swpmcs数据库没有。所以,如果我执行脚本,我会有一个错误,它不会提交。

我知道postgres 9有可能DROP CONSTRAINT IF EXISTS,但postgres 8Oracle 11g都没有这个功能。 我工作和学习SQL只有3个月,我知道这很简单,但对我来说这是一个问题。

感谢您的帮助

1 个答案:

答案 0 :(得分:4)

这是您将得到的错误:

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

您可以在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.

这有点冗长,所以你可以创建一个方便的程序:

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;

然后在需要时使用它:

execute drop_constraint ('my_tab', 'my_cons1');
execute drop_constraint ('my_tab', 'my_cons2');
execute drop_constraint ('another_tab', 'another_cons');