使用主外來鍵約束使得資料具有完整性。
1、查詢表上所有的約束
select * from user_constraints t
where t.table_name='father';
2、查詢具有主外來鍵關係的表
select c.owner,c.constraint_name,c.constraint_type,c.table_name,f.owner,f.constraint_name,f.constraint_type,f.table_name
from dba_constraints c, dba_constraints f
where c.r_owner=f.owner
and c.r_constraint_name=f.constraint_name
and c.table_name='child'; --查詢子表child對應的所有父表
3、子表中插入的記錄必須在父表中存在,否則會報parent key not found
sql> insert into child values ('datong',1);
insert into child values ('datong',1)
*error at line 1:
ora-02291: integrity constraint (scott.fk_addr) violated - parent key not found
4、父表的記錄只有在子表中找不到才可以刪除,否則會報child record found
sql> delete from father where id=1;
delete from father where id=1
*error at line 1:
ora-02292: integrity constraint (scott.fk_id) violated - child record found
sql> delete from father where id=2;
1 row deleted.
sql> commit;
commit complete.
5、如何完全刪除父表資料,如truncate、drop
sql> truncate table father;
truncate table father
*error at line 1:
ora-02266: unique/primary keys in table referenced by enabled foreign keys
針對上面情況,可以先將father表的所有子表的引用約束disable,使用下面的sql得到禁用子表約束語句:
select 'alter table '||c.owner||'.'||c.table_name||' modify constraint '||c.constraint_name||' disable;' "exec_sql"
from user_constraints c, user_constraints f
where c.r_owner=f.owner
and c.r_constraint_name=f.constraint_name
and f.table_name='father';
exec_sql
alter table scott.child modify constraint fk_id disable;
然後執行上面的查詢結果,就可以禁掉所有的子表約束,truncate父表就不會報錯了。
sql> alter table scott.child modify constraint fk_id disable;
table altered.
sql> truncate table father;
table truncated.
當然,此時子表的引用約束不一定能起來(enable),取決於子表是否有資料。
sql> alter table scott.child modify constraint fk_id enable;
alter table scott.child modify constraint fk_id enable
*error at line 1:
ora-02298: cannot validate (scott.fk_id) - parent keys not found
將子表資料全部刪除,就可以起來(enable)子表的引用約束。
sql> truncate table child;
table truncated.
sql> alter table scott.child modify constraint fk_id enable;
table altered.
sql> drop table father;
drop table father
*error at line 1:
ora-02449: unique/primary keys in table referenced by foreign keys
這種情況可以使用cascade constraints子句一同將子表的引用約束刪掉。
sql> drop table father cascade constraints;
table dropped.
Oracle檢視主外來鍵
select a.constraint name,a.table name,b.constraint name from user constraints a,user constraints b where a.constraint type r and b.constraint type p a...
oracle 檢視主外來鍵約束
select a.constraint name,a.table name,b.constraint name from user constraints a,user constraints b where a.constraint type r and b.constraint type p a...
mysql建立主外來鍵關聯 mysql主外來鍵建立心得
mysql主主外來鍵建立 1 確保參照的表和字段是存在的 2 關聯表必須是innodb儲存型別 3 必須設定主關聯表主鍵 4 主鍵與外來鍵資料型別和字元編碼 unsigned 必須一致 5 確保以上宣告的句法是正確的 附 mysql建立表預設型別為 myisam 如果要改變預設表型別可在my.inf...