如何为新数据设置外键约束



我有一个表(T1),该表上有一些记录。我想为一列(c1)创建外键约束,但我想忽略现有记录(旧记录)的约束。我的意思是FK约束应该适用于新记录。

有可能吗?

您可以在Oracle中使用NOVALIDATE关键字创建约束,忽略任何预先存在的坏数据,但对任何插入或更新强制执行,例如:

create table t1 (id number primary key);
create table t2 (id2 number primary key, id number not null);
insert into t2 values (1,1);
alter table t2 add constraint t2_fk
  foreign key (id)
  references t1 (id)
  novalidate;
insert into t2 values (2,2);
ORA-02291: integrity constraint (SCOTT.T2_FK) violated - parent key not found

唯一的缺点是Oracle优化器在做决策时不能使用该约束。因此,在添加已验证约束之前,最好尽可能修复现有数据。

SebastianH的解决方案很好。如果不能创建表,另一个解决方案是使用触发器来完成这项工作。这个解决方案的问题是主表的删除行问题。可以用另一个触发器处理

最新更新