---创建学生表(son学号 sname姓名 ssex性别 smajor专业 sage学号)
create table student
(
sno char(20) not null primary key,
sname char(20) not null,
ssex char(2) not null default '男',
smajor char(12) null,
sage int null
);
---创建学生信息
insert into student
values('2023006','欧阳明月','男','计算机',19),
('2023001','张三','男','计算机',19),
('2023002','李四','男','物理',20),
('2023003','王五','男','化学',23),
('2023004','李华','女','计算机',20),
('2023005','冯涛','男','通信',19);
select *from student;
---创建选课表(sno学号 cno课号 grade成绩)
create table sc
(
sno char(20) not null,
cno char(4) not null,
grade tinyint null,
);
--1、创建触发器
--[例1]Student中创建DML触发器stu_unupdate,禁止修改学号Sno、姓名Sname字段。
go
create trigger stu_unupdate on student
after update
as
--执行语句
if update(sno) or update(sname)
print('禁止修改学号 姓名')
rollback;
go
--触发语句
update student
set sno ='002'
where sno ='2023002'
--[例2] 在teach数据库的“学生”表Student中创建DML触发器stu_insert,
--给表中每添加一条信息时,自动查看所有学生信息
go
create trigger stu_insert on student
after insert
as
--执行语句
select *from student
go
--触发语句
insert into student(sno,sname)
values('2023023','赵'),('20239999','王柳');
--[例3]创建触发器,实现禁止删除课程号为1的课程信息
go
create trigger cou_cno on course
after delete
as
--执行语句
if delete (cno=1)
print('禁止删除课程号为1的课程信息')
rollback;
go
--[例4]设计一个触发器完成上述功能:假设student表,
--当删除某一同学sno时,该同学的所有选课也都要删除。
go
create trigger stu_delete on student
after delete
as
--执行语句
--定义变量,代表删除的学号
declare @sno_old varchar(20)
--初始化
select @sno_old = sno from deleted
delete from sc
where sc.sno = @sno_old
go
--触发语句
delete from student
where sno ='2023005'
select *from student
--[例5]创建触发器,假设student表中某一学生要变更其主码sno的值,
--如使其原来的20210023变更为20210056,
--此时sc表中该同学已选课记录的sno也需自动随其改变。
go
create trigger stu_update on student
after update
as
--执行语句
--定义2个变量,代表修改前、修改后的学号
declare @sno_old varchar(20)
declare @sno_new varchar(20)
--初始化
select @sno_old = sno from deleted
select @sno_new = sno from inserted
update sc
set sc.sno = @sno_new
where sc.sno =@sno_old
--触发语句
update student
set sno='666'
where sno ='2023001'

云探网文章。发布者:ziqiu,转转请注明出处:https://www.zeauo.cn/archives/4035.html