按照第五版数据库系统概论的教材的例题在SQL sever上写,无一例外全部报错。
借鉴某些博客和自己的摸索探索出了一个模板和几个套路。
模板:
create trigger xxx on (table) --xxx是触发器的名字,table指要操作的表
for/before/after --三种模式,后面的操作进行之时,进行之前,进行之后
insert/update/deleted --插入数据触发,更新数据触发,删除数据触发,这三种操作指的就是上面提到的后面的操作
begin -- 相当于前括号
declare @a datetime --定义一个变量,做中间处理
declare @b char(40)
select @a = a,@b = b from inserted --插入数据时,插入的数据在表inserted
--更新数据时,更新后的数据在表inserted,更新前的数据在表中deleted
--删除数据时,删除的数据在表deleted
--不同的操作可以取出不同的中间数据做处理,例子中是取出插入的数据
触发器的限制:(触发器是一种特殊的储存过程)
一个表最多只能有三个触发器,insert,update,delete
●每个触发器只能用于一个表
●不能对视图、临时表创建触发器
●不能将触发器用于系统表
举个例子:
先建表
CREATE TABLE STUDENT
(
SNO CHAR(10),
SNAME CHAR(10),
SSEX CHAR(10),
SAGE INT,
SDEPT CHAR(10),
SCLASS CHAR(10),
STOTAL INT
)
insert into student values ('20100001','李勇','男',20,'CS','1001',0)
insert into student values ('20100002','刘晨','女',19,'CS','1001',0)
insert into student values ('20100003','刘洋','女',null,null,'1001',0)
insert into student values ('20100010','赵斌','男',19,'IS','1005',0)
insert into student values ('20100021','王敏','女',18,'MA','1002',0)
insert into student values ('20100022','张明明','男',19,'CS','1002',0)
insert into student values ('20100031','张立','男',19,'IS','1003',0)
insert into student values ('20120010','赵斌','男',19,'IS','1005',0)
select * from student
create table course
(
cno char(10),
cname char(10),
cpno int,
ccredict int
)
insert into course values ('1','数据库',5,4)
insert into course values ('2','数学',null,2)
insert into course values ('6','数据处理',null,2)
insert into course values ('4','操作系统',6,3)
insert into course values ('7','c语言',null,4)
insert into course values ('5','数据结构',7,4)
insert into course values ('3','信息系统',1,4)
select * from course
create table sc
(
sno char(10),
cno char(10),
grade int
)
insert into sc values ('20100001','1',92)
insert into sc values ('20100001','2',85)
insert into sc values ('20100001','3',88)
insert into sc values ('20100002','1',90)
insert into sc values ('20100002','2',80)
insert into sc values ('20100003','1',null)
insert into sc values ('20120010','3',null)
select * from sc
--定义一个触发器,实现有关学分的完整性约束:当向SC表插入一行选课记录时,
--自动将该课程的学分累加到该学生的总学分中。
create trigger insert_add on sc
for insert
as
begin
declare @sno char(10)
declare @cno char(10)
select @sno = sno,@cno = cno from inserted
update student set stotal = stotal + (select course.ccredit from course where cno = @cno)
where sno = @sno
end
//检测
insert into sc values('20100001','1','99')
select * from course
select * from sc
select * from student
--定义一个触发器,实现对SC表的操作登记:当用户向SC表插入或修改时,记录该操作到数据库中
create table temp_table
(
username char(10),
date datetime,
tsno char(10),
tcno char(10)
)
create trigger document_sc on sc
for insert,update
as
begin
declare @sno char(10)
declare @cno char(10)
declare @date char(30)
select @sno = sno,@cno = cno from inserted
insert into temp_table values (CURRENT_USER,(select getdate()),@sno,@cno)
end
//检测
insert into sc values('20100001','1','99')
select * from temp_table