最近在客户的项目里又用到了触发器,总结一下。
1、触发器是什么:
触发器是一种特殊类型的存储过程,它在您使用一种或多种数据修改操作(UPDATE、INSERT 或 DELETE)来修改指定表中的数据时运行。
2、触发器语法:
1 CREATE TRIGGER authors_Trigger1 2 ON dbo.authors 3 FOR /* INSERT, UPDATE, DELETE */ 4 AS 5 /* IF UPDATE (column_name) . . .*/
或
1 CREATE TRIGGER titleview_Trigger1 2 ON dbo.titleview 3 INSTEAD OF /* INSERT, UPDATE, DELETE */ 4 AS 5 /* IF UPDATE (column_name) . . .*/
3、触发器种类
Instead of 和 After两种
Instead of触发器:插入真正的操作之前执行。
After:在执行完指定的操作以后执行
1 --1、Instead of 触发器 2 create trigger trigger_Student 3 on student 4 instead of delete 5 as 6 begin 7 select * from Student 8 end 9 10 delete from student where id = 1 11 --执行Delete操作,实际执行了Select操作
1 --2、After触发器 2 alter trigger After_Trigger 3 on student 4 after update 5 as 6 begin 7 insert into studentinfo(name,school) (select Name,School from inserted where FStatus = 1 and Name not in(select name from StudentInfo)) 8 end
SQL Server为每个触发器都创建了两个专用表:Inserted表和Deleted表。
Inserted: insert和update之后的新值集合
Deleted:delete和update之前的旧值集合
例如:更新Student表中ID为1的学生姓名为Jake
student表
ID | Name | Age | School | FStatus |
1 | HelloWorld | 20 | 湖南 学校 | 1 |
1 --创建触发器 2 create trigger trigger_1 3 on student 4 after update 5 as 6 begin 7 select * from inserted 8 end
更新时会显示如下值:
1 update Student set Name = 'Jake' where id = 1
Id | Name | Age | School | FStatus |
1 | Jake | 20 | 湖南学校 | 1 |
1 alter trigger trigger_1 2 on student 3 after update 4 as 5 begin 6 select * from deleted 7 end
更新时会显示如下值:
update Student set Name = 'Jake' where id = 1
Id | Name | Age | School | FStatus |
1 | HelloWorld | 20 | 湖南学校 | 1 |