1. 程式人生 > >SQL SERVER 主鍵和外來鍵中的 級聯刪除(ON DELETE CASCADE)和級聯更新(ON UPDATE CASCADE)

SQL SERVER 主鍵和外來鍵中的 級聯刪除(ON DELETE CASCADE)和級聯更新(ON UPDATE CASCADE)

建立學生表
create table gh_student(
stuno varchar(3) primary key,
stuname varchar(4),
stuclass varchar(3)
)

插入資料

insert into gh_student values('001','gh','101')
insert into gh_student values('002','lxg','102')
insert into gh_student values('003','hs','103')

建立成績表
create table gh_grade(
grade_stuno varchar(3) ,
grade_lessonno varchar(3) ,
grade  varchar(3)
)

插入資料
insert into gh_grade values('001','yw','98')
GO
insert into gh_grade values('001','yy','99')
GO
insert into gh_grade values('001','sx','94')
GO
insert into gh_grade values('002','yw','93')

insert into gh_grade values('002','yy','95')

insert into gh_grade values('002','sx','96')


在成績表上建立外來鍵約束 這裡是級聯更新
alter table gh_grade add constraint FK_StudentNo foreign key (grade_stuno) references gh_student (stuno) ON UPDATE CASCADE


此時執行select * from gh_grade

原始結果如下

grade_stuno grade_lessonno grade
001                yw                       98
001                yy                        99
001                sx                        94
002                yw                       93
002                yy                        95
002                sx                        96

注意此時演示級聯更新

 執行sql:update gh_student set stuno='008' where stuname='gh'

再次執行查詢語句:select * from grade

結果如下

grade_stuno grade_lessonno grade
008                yw                       98
008                yy                        99
008                sx                        94
002                yw                       93
002                yy                        95
002                sx                        96


接下來演示級聯刪除

建立級聯刪除

alter table gh_grade DROP constraint FK_StudentNo

alter table gh_grade add constraint FK_StudentNo foreign key (grade_stuno) references gh_student (stuno) ON DELETE CASCADE

然後執行sql:DELETE FROM gh_student WHERE stuno='001'

再次執行查詢:select * from grade

結果如下

grade_stuno grade_lessonno grade
002                     yw                 93
002                     yy                  95
002                     sx                  96


總結:所謂的級聯更新,就是更新主鍵表(gh_student )的同時,外來鍵表(grade)同時更新。

所謂的級聯刪除,就是刪除主鍵表(gh_student )的同時,外來鍵表(grade)同時刪除。


這裡還要注意:當學生表(gh_student )中沒有('001','gh','101')這條記錄時,成績表(grade)中這三條插入語句是插不進去的,會報衝突,成績表會自動判斷沒有001這個學生。

insert into gh_grade values('001','yw','98')
GO
insert into gh_grade values('001','yy','99')
GO
insert into gh_grade values('001','sx','94')
GO