速掌握DB2資料庫建立外來鍵時的選項

2021-05-10 13:31:03 字數 1386 閱讀 8891

教你快速掌握db2資料庫建立外來鍵時的選項

建立外來鍵時的選項:

1.建立測試表:

drop table student;

drop table class; 

drop table student_class; 

create table student(student_id integer not null,student_name varchar(200), constraint p_key_1 primary key (student_id)) in luzl_32k_tb index in luzl_32k_tb ; 

create table class(class_id integer not null,class_name varchar(200), constraint p_key_2 primary key (class_id))  ; 

create table student_class(student_class_id integer,student_id integer,class_id integer) ; 

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_id,student_name) values(1,'luzl');

insert into class(class_id,class_name) values(1,'db2'); 

insert into student_class(student_class_id,student_id,class_id) values(1,1,1); 

2.on delete 的選項有:

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

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

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

建立 DB2 資料庫

可以使用 tivoli privacy manager 資料庫建立程式或使用資料庫產品介面可以建立 tivoli privacy manager 資料庫 表和配置資料庫。使用 db2 資料庫建立程式 使用 tivoli privacy manager 資料庫建立程式來建立 tivoli privac...

建立DB2資料庫

建立db2資料庫 1.建立資料庫 db2cmd db2 list db directory 查詢現存的資料庫 create db dbname 建立資料庫 2.建立使用者名稱密碼 方法一 db2cmd db2cc 選擇建立好的資料庫 使用者和組物件 資料庫使用者中新建 我的電腦 管理 本地使用者和組...

DB2 資料庫建立

登入資料庫管理使用者 db2inst db2 db2inst db2 create database dbname automatic storage yes on dbauto dbpath on database using codeset gbk territory cn collate us...