SQL> create table a (id number);
Table created.
SQL> alter table a add constraint pk_a primary key(id);
Table altered.
SQL> create table b (bid number references a (id));
Table created.
SQL> insert into a values (1);
1 row created.
SQL> commit;
Commit complete.
SQL> insert into b values (1);
1 row created.
SQL> commit;
Commit complete.
SQL> drop table a ;
drop table a
*
ERROR at line 1:
ORA-02449: unique/primary keys in table referenced by foreign keys
/*因为有外键对a表进行引用而无法drop。*/
SQL> delete from a;
delete from a
*
ERROR at line 1:
ORA-02292: integrity constraint (SYS.SYS_C005401) violated - child record found
/*因为有外键数据对a表的数据进行引用,数据无法delete*/
SQL> alter table a disable constraint pk_a;
alter table a disable constraint pk_a
*
ERROR at line 1:
ORA-02297: cannot disable constraint (SYS.PK_A) - dependencies exist
/*由于对约束有依赖关系,约束无法disable*/
SQL> alter table b disable constraint SYS_C005401;
Table altered.
SQL> drop table a purge;
drop table a purge
*
ERROR at line 1:
ORA-02449: unique/primary keys in table referenced by foreign keys
/*即使禁用了外键约束,由于外键约束依然存在,也无法将主表drop。*/
SQL> delete from a ;
1 row deleted.
SQL> commit;
Commit complete.
SQL> delete from b;
1 row deleted.
SQL> commit;
Commit complete.
SQL> drop table a;
drop table a
*
ERROR at line 1:
ORA-02449: unique/primary keys in table referenced by foreign keys
/*即使主表跟外键表都没有了数据,外键约束被禁用,也无法drop主表。*/
SQL> alter table a disable constraint pk_a;
Table altered.
/*当外键约束被禁用之后,主键约束也能够禁用了。*/
SQL> drop table b;
Table dropped.
SQL> drop table a;
Table dropped.
SQL>
SQL> create table a (id number);
Table created.
SQL> alter table a add constraint pk_a primary key(id);
Table altered.
SQL> create table b (bid number);
Table created.
SQL> alter table b add constraint fk_bid foreign key(bid) references a(id) on delete cascade;
Table altered.
SQL> insert into a values (1);
1 row created.
SQL> commit;
Commit complete.
SQL> insert into b values (1);
1 row created.
SQL> commit;
Commit complete.
SQL> delete from a;
1 row deleted.
SQL> commit;
Commit complete.
SQL> select * from b;
no rows selected
/*级联删除,还有on update cascade 级联更新。*/
结论:
不管我们是禁用约束、删除数据,drop表,都必须先完成外键表的约束禁用、数据删除、表DROP,才能相应的完成主键表的操作。当然如果我们是删除数据的话,也可以先将约束禁用了,然后执行数据删除操作,这个时候可以无序删除。但是如果我们是DROP表的话,必须先DROP外键约束,或者先DROP外键表,才能DROP主键表,光禁用外键约束是不行的。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/23135684/viewspace-670616/ ,如需转载,请注明出处,否则将追究法律责任。