Chinaunix首页 | 论坛 | 博客
  • 博客访问: 447032
  • 博文数量: 135
  • 博客积分: 4177
  • 博客等级: 上校
  • 技术积分: 1145
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-13 17:16
文章分类

全部博文(135)

文章存档

2011年(5)

2010年(4)

2009年(26)

2008年(25)

2007年(29)

2006年(42)

2005年(4)

分类: Oracle

2006-02-13 18:09:51

當你要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

SQL> insert into t values(3,linus);
insert into t values(3,linus)
                       *
ERROR 位于第 1 行:
ORA-00984: 列在此处不允许

--错误查询

或是违反了constraint,primary key中是不能添加新的字节的吗?先看清楚primary key 与foreign key的详细函义!

利用SQL> insert into t(id,name) values(4,mike);
insert into t(id,name) values(4,mike)
                                *
ERROR 位于第 1 行:
ORA-00984: 列在此处不允许

SQL> insert into t (id,name) values(4,'mike');

已创建 1 行。

详细的问题目已记录;(请记住此问题的发生,不要发生第二次了)

(違反了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。

阅读(923) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~