跟著小郭郭一起學 SQL Server-15 Foreign Key(1)

三折肱而成良醫

在上回我們介紹了 Primary Key 約束是什麼,以及如何建立、檢視與刪除 Primary Key,
接下來我們將介紹什麼是 Foreign Key。


Foreign Key 約束會將能進入一個欄位的資料局限於是一個會另一張表的特定欄位裡所有的資料的約束,當我們輸入資料時, SQL Server 就會參照另一個欄位,確認那個欄位有這筆資料才會成功,沒有這筆資料時,該筆資料就沒辦法輸入。而我們稱被參照的來源資料表為 Parent,實際套用約束的資料表則是稱為 Child
所以當我們要建立與測試 Foreign Key 約束前,我們要先建立這個約束要參照資料表與欄位,這個欄位必須是該資料表的 Primary Key,並且這兩個資料型態必須相同。
請打開 New Query 後,複製下列文字並按下 F5 執行:

Create Table Foreign_Key_test_Parent
(
	Student_ID int Not Null Primary Key,
	Student_Name nvarchar(50),
	Date_of_Birth date
)

INSERT INTO Foreign_Key_test_Parent (Student_ID,Student_Name,Date_of_Birth)Values

('1001','Jeff','2022/02/13'),
('1002','Lily','2022/02/14'),
('1003','Tochter','2022/02/15')
SELECT TOP (10) * From Foreign_Key_test_Parent

這樣我們就可以確認資料表已經建立,並且裡面的 Student_ID 有 1001~1003了。

接下來,我們來建立實際使用 Foreign Key 約束的資料表,並在建立資料表時對欄位加入Foreign Key 約束,加入的格式如下:
欄位名稱 資料類型 是否允許 NUll

Constraint 約束名稱 Foreign Key References 資料表(欄位)

請打開 New Query 後,複製下列文字並按下 F5 執行:

Create Table Foreign_Key_test_Child
(
	Student_ID int Not Null 
	Constraint Foreign_Key_Student_ID Foreign Key References Foreign_Key_test_Parent(Student_ID),
	Course_ID  nvarchar(50) Not Null,
	Score CHAR(5)
	
);

INSERT INTO Foreign_Key_test_Child (Student_ID,Course_ID,Score)Values
('1001','0020','A'),
('1002','0020','B'),
('1003','0020','C'),

SELECT TOP (10) * From Foreign_Key_test_Child 

這樣就可以看到 1001~1003 的資料都有被成功寫入。接下來我們輸入一筆不存在於 Parent 資料表的欄位的資料。

請打開 New Query 後,複製下列文字並按下 F5 執行:

INSERT INTO Foreign_Key_test_Child (Student_ID,Course_ID,Score)Values

('1004','0020','D')

就會看到被擋下來的錯誤訊息。

接下來則是如何檢視已經被建立的 Foreign Key,一種方式是直接到資料表的 Keys 中檢視。


另一種則是透過 information schema 查詢,請打開 New Query 後,複製下列文字並按下 F5 執行:

Select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE

刪除 Foreign Key 則是使用 Alter table 資料表名稱 Drop constraint Foreign Key 名稱,

請打開 New Query 後,複製下列文字並按下 F5 執行:

Alter table Foreign_Key_test_Child
Drop constraint Foreign_Key_Student_ID

INSERT INTO Foreign_Key_test_Child (Student_ID,Course_ID,Score)Values

('1004','0020','D')

SELECT TOP (10) * From Foreign_Key_test_Child 

就可以看到約束消失,剛才因為約束無法被 insert 的資料可以成功insert 了。

而同樣使用 Alter Table 指令則可以再把 Foreign Key 加回來,
請打開 New Query 後,複製下列文字並按下 F5 執行:

Delete Foreign_Key_test_Child 

Alter table Foreign_Key_test_Child
ADD constraint Foreign_Key_Student_ID
Foreign Key(Student_ID)  References Foreign_Key_test_Parent(Student_ID);
INSERT INTO Foreign_Key_test_Child (Student_ID,Course_ID,Score)Values

('1004','0020','D')

OK,這就是今天的內容,接下來我們將會開始講解如何在資料表中查詢/新增/修改/刪除資料。

發表留言