熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> DB2 >> 正文

教你快速掌握DB2數據庫創建外鍵時的選項

2022-06-13   來源: DB2 
    免費看《Windows CE 嵌入式系統開發從基礎到實踐》

  創建外鍵時的選項

  創建測試表

  drop table student;
  drop table class;
  drop table student_class;
  Create table student(student_id integer not nullstudent_name varchar() CONSTRAINT P_KEY_ primary key (student_id)) in luzl_k_tb index in luzl_k_tb ;
  Create table class(class_id integer not nullclass_name varchar() CONSTRAINT P_KEY_ primary key (class_id)) in luzl_k_tb index in luzl_k_tb ;
  Create table student_class(student_class_id integerstudent_id integerclass_id integer) in luzl_k_tb index in luzl_k_tb;
  alter table student_class add constraint if_class foreign key(class_id) references class(class_id) ON DELETE cascade ON UPDATE RESTRICT;
  alter table student_class add constraint if_student foreign key(student_id) references student(student_id) ON DELETE cascade ON UPDATE RESTRICT;
  Insert into student(student_idstudent_name) values(luzl);
  Insert into class(class_idclass_name) values(db);
  Insert into student_class(student_class_idstudent_idclass_id) values();

  On Delete 的選項有

  Restrict/no action/cascade/set null其中cascade選項指定的話如果刪除父記錄依賴於他的子記錄也會自動刪除相當於級聯刪除如果指定no action和cascade都會報錯因為還有子記錄所以無法刪除該記錄set nul允許刪除父記錄並且l會將子表中與父表關聯的字段設置為null

  On Update 只有兩個選項 no action/restrict它們在更新和刪除時並沒有區別:如果與子表關聯不允許刪除

  另外還需要注意一點父表中的字段必須是主鍵才能做為子表的外鍵


From:http://tw.wingwit.com/Article/program/DB2/201311/21928.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.