触发器是一类特殊的存储过程,在对表update,insert或delete语句时自动执行, 没有参数,没有返回值;
一、触发器类型
1、for触发器
在动作执行之后触发(增删改执行完成后,触发器中的代码再执行),不能为视图指定for触发器,只能为表指定该触发器。
2、instead of触发器
可以理解为替代触发操作执行,写了这个之后,写的执行代码就没有用了,就被触发器的代码覆盖了
二、创建触发器
create trigger Insert_Student --命名规范
on student --针对于哪一个表
for insert --针对于哪一个动作来触发
as
触发执行的代码段
go
例如:
create trigger Delete_Info on info instead of delete as go create trigger Delete_Nation on nation for delete as go
注:触发器常用的为级联删除:
create trigger delete_student
on student
instead of delete
as
--如果要删除student表数据,那么需要级联删除
declare @sno varchar(20);
set @sno = sno from deleted --deleted固定格式,为删除执行所能删除的数据,并没有执行删除,而是把他们显示出来,在这获得要删除的数据的sno,然后先删除其他表中此sno的数据
delete from score where sno = @sno;
delete from student where sno = @sno;
go
例如:
create trigger Delete_Info on info instead of delete as declare @c varchar(20) select @c = code from deleted delete from work where infocode=@c delete from family where infocode=@c delete from info where code=@c go