一、sql server中建立外來鍵約束有3中方式i
阿新 • • 發佈:2018-12-20
一、sql server中建立外來鍵約束有3中方式
1.Enterprise Manager中,Tables,Design Table,設定Table的properties, 可以建立constraint, reference key;
2.Enterprise Manager中,Diagrams, new Diagrams,建立兩個表的關係。
3.直接用transact sql語句。
二、子表,父表的定義
擁有外來鍵的表是子表。主鍵被其它表引用的表是父表。因為父表的標識被很多個子表中的記錄引用,所以叫父表。擁有外來鍵關係,並且可以隨便刪除資料,不影響其它表的資料的那個表叫子表。
三、使用的時候誰做為誰的外來鍵,主要從以下兩點考慮
1、刪除是如何相互影響的,刪除記錄受約束的那個是父表,不受約束的那個是子表; 2、記錄必須先存在的是父表;
四、外來鍵約束的用途:
1、建立中檢查現存資料 建立關係時將關係應用於外來鍵表中的現有資料。如果選定該對話方塊,一個錯誤資訊將會通知您有違反約束的資料。
2、對 INSERT 和 UPDATE 強制關係 如果選擇該選項,則只要使用這些語句在外來鍵表中新增或更新資料時都將強制約束。
3、對複製強制關係 如果選擇該選項,則無論何時將外來鍵表複製到一個不同的資料庫,都將強制關係的引用完整性。
4、級聯更新相關的欄位 無論何時更新主鍵值,都指示資料庫將新的鍵值傳播到相應的外來鍵欄位。
5、級聯刪除相關的欄位 無論何時刪除主表中的行,都指示資料庫從外來鍵表中刪除相應的行。
五、一個SQL建立外來鍵的例子
SQL 程式碼 複製
/*建庫,名為student_info*/ create database student_info /*使用student_info*/ use student_info go /*建student表,其中s_id為主鍵*/ create table student ( s_id int identity(1,1) primary key, s_name varchar(20) not null, s_age int ) go /*建test表,其中test_no為主鍵*/ create table test ( test_no int identity(1,1) primary key, test_name varchar(30), nax_marks int not null default(0), min_marks int not null default(0) ) go /*建marks表,其中s_id和test_no為外建,分別對映student表中的s_id和test表中的test_no*/ create table marks ( s_id int not null, test_no int not null, marks int not null default(0), primary key(s_id,test_no), foreign key(s_id) references student(s_id), foreign key(test_no) references test(test_no) ) go