- 71
- 0
- 约4.98千字
- 约 5页
- 2021-11-12 发布于山东
- 举报
7实验七触发器
7实验七触发器
PAGE / NUMPAGES
7实验七触发器
实验七 触发器
一、实验目的
1)理解触发器的用途、类型和工作原理
2)掌握利用 T-SQL语句创建和维护触发器的方法
3)掌握利用企业管理器创建、维护触发器的方法二、实验内容
创建 after 触发器
(1 )创建一个在插入时触发的触发器
sc_insert,
当向 sc 表插入数据时, 须确保插入的学号已在
Student
表中存在,并且还须确保插入的课程号在
Course 表中存在;若不存在,则给出相应的提示信息,并取消插
入操作,提示信息要求指明插入信息是学号不满足条件还是课程号不满足条件(注:
Student
表与 sc 表的
外键约束要先取消)。
create
on sc
after
as
if not
trigger
insert
exists(
sc_insert select
* from
student
, inserted
where
=
begin
print
if
插入信息的学号不在学生表中!
not exists( select * from course
print 插入信息的课程号不在课程表中!
, inserted
where
=
rollback
end
else
begin
if not exists( select * from course , inserted where = begin
print 插入信息的课程号不在课程表中!
rollback
end
end
执行:
①、 insert values
into
(, 001
SC
, 78
)
删除外键约束:
alter
table
SC
drop constraint FK__SC__Sno__182C9B23
②、 insert into SC
values (, 001 , 78 )
③、 insert into SC
values ( , 006 , 78 )
(2 )为 Course 表创建一个触发器 Course_del
,当删除了
Course 表中的一条课程信息时,同时将表
sc 表
中相应的学生选课记录删除掉。
create
trigger
course_del
on course
after delete
as
if exists(
select
where
* from =
sc , deleted
begin
delete from sc
where in( select cno from deleted )
end
delete from Course
where Cno = 003
select * from SC
(3 )在 Course 表中添加一个平均成绩 avg_Grade 字段(记录每门课程的平均成绩),创建一个触发器
Grade_modify ,当 SC表中的某学生的成绩发生变化时, 则Course 表中的平均成绩也能及时相应的发生改变。
alter table Course
add avg_Grade smallint
update Course
set avg_Grade =( select AVG( Grade ) from SC
where =
select * from Course
create trigger Grade_modify
on sc
after update
as
if update ( grade )
begin
update course
set avg_grade =( select
from
group
sc
by
avg ( grade where = cno )
)
end
update SC
set Grade = 90
where Sno = and
Cno = 001
( 4)测试上述三个触发器。
测试过程在( 1)、( 2)、( 3)中均给出
2. 创建 instead of
触发器
(1 )创建一视图 Student_view,
包含学号、姓名、课程号、课程名、成绩等属性,在
Student_view 上
创建一个触发器
Grade_moidfy ,当对 Student_view
中的学生的成绩进行修改时,实际修改的是
sc 中的相应
记录。
create
view
Student_view
as
select
, Sname ,, Cname , Grade
from
Student
s , Course c , SC
where
= and
=
select
*
from
Student_
原创力文档

文档评论(0)