談一談SQL Server數(shù)據(jù)庫(kù)創(chuàng)建外鍵約束時(shí)的兩個(gè)小應(yīng)用
在SQL Server數(shù)據(jù)庫(kù)操作中,我們?cè)趧?chuàng)建外鍵約束時(shí),如果想在刪除記錄時(shí)同時(shí)級(jí)聯(lián)刪除受影響的記錄,可以使用on delete cascade語(yǔ)句來(lái)實(shí)現(xiàn),如果想在刪除記錄時(shí)設(shè)置受影響的外鍵字段為空,可以使用on delete set null,本文介紹了這一過(guò)程,希望能夠帶給您一些收獲。
on delete cascade:
外鍵指向記錄被刪除時(shí)級(jí)聯(lián)刪除受影響記錄。
- alter table emp
- add constraint fk_emp_dept foreign key(dept) references dept(deptno) on delete cascade;
刪除dept的記錄時(shí)級(jí)聯(lián)刪除emp數(shù)據(jù)。
on delete set null:
外鍵指向記錄被刪除時(shí)設(shè)置受影響記錄外鍵字段為空。
- alter table emp
- add constraint fk_emp_dept foreign key(dept) references dept(deptno) on delete set null;
刪除dept的記錄時(shí)emp中參照這條數(shù)據(jù)的兩條數(shù)據(jù)的dept的值被自動(dòng)賦空。
關(guān)于SQL Server數(shù)據(jù)庫(kù)創(chuàng)建外鍵約束的兩個(gè)小應(yīng)用就介紹這么多,如果您想了解更多的關(guān)于SQL Server數(shù)據(jù)庫(kù)的內(nèi)容,可以看一下這里的文章:http://database.51cto.com/sqlserver/,相信一定會(huì)帶給您收獲的。
【編輯推薦】