ORACLE中Drop table cascade constraints之后果.

当你要drop一个table时,如果删除table的动作会造成trigger或constraint产生矛盾,系统会出现错误警告的讯息而不会允许执行.。一个极简单的例子,例如你有一个员工基本资料表,上面可能有员工编号和员工姓名等字段,另外有一个员工销售表,上面有员工编号和员工销售额两个字段,员工薪资表的员工编号字段为一个foreign key参照到员工基本资料表的员工编号:

SQL> drop table t;

Table dropped.

SQL> drop table t1;

Table dropped.

SQL> create table t (id number,name varchar2(20));

Table created.

SQL> create table t1 (id number,sal number);

 

Table created.

SQL> alter table t add constraint t_pk primary key (id);

Table altered.

SQL> alter table t1 add constraint t_fk foreign key (id) references t (id);

Table altered.

SQL> insert into t values (1,'JACK');

1 row created.

SQL> insert into t values (2,'MARY');

1 row created.

SQL> COMMIT;

Commit complete.

SQL> insert into t1 values (1,1000);

1 row created.

SQL> insert into t1 values (2,1500);

1 row created.

SQL> commit;

SQL> insert into t1 values (3,200); 
insert into t1 values (3,200) 

ERROR at line 1: 
ORA-02291: integrity constraint (SYS.T_FK) violated - parent key not found

(違反了constraint,員工基本資料表根本沒有3號這個員工,何來的銷售紀錄。)

SQL> drop table t; 
drop table t 

ERROR at line 1: 
ORA-02449: unique/primary keys in table referenced by foreign keys

(违反了constraint,员工销售表t1有參照到table t,这个reference relation不允许你drop table t)

SQL> drop table t cascade constraints;

Table dropped.

SQL> select * from t1;

ID SAL 
---------- ---------- 
1 1000 
2 1500

SQL> select CONSTRAINT_NAME,TABLE_NAME from dba_constraints where owner = 'SYS' and TABLE_NAME = 'T1'

no rows selected

SQL>

我们可以发现利用Drop table cascade constraints可以以刪除关联table t的constraint來达成你drop table t的目的,原來属于t1的foreign key constraint已经跟随着被删除掉了,但是,储存在table t1的资料可不会被删除,也就是说Drop table cascade constraints 是不影响到存储于objec里的row data。

上一篇:对python中元类的理解


下一篇:Windows Phone开发(22):启动器与选择器之BingMapsDirectionsTask