触发器: 在 SQL Server 里面也就是对某一个表的一定的操作,触发某种条件,从而执行的一段程序。触发器是一个特殊的存储过程。
<!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:Calibri; mso-font-alt:"Century Gothic"; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:-1610611985 1073750139 0 0 159 0;} @font-face {font-family:"/@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.5pt; mso-bidi-font-size:11.0pt; font-family:Calibri; mso-fareast-font-family:宋体; mso-bidi-font-family:"Times New Roman"; mso-font-kerning:1.0pt;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:612.0pt 792.0pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:36.0pt; mso-footer-margin:36.0pt; mso-paper-source:0;} div.Section1 {page:Section1;} -->
常见的触发器有三种:分别应用于 Insert , Update , Delete 事件。
我为什么要使用触发器?比如,这么两个表:
Create Table Student( -- 学生表
StudentID int primary key, -- 学号
....
)
Create Table BorrowRecord( -- 学生借书记录表
BorrowRecord int identity(1,1), -- 流水号
StudentID int , -- 学号
BorrowDate datetime, -- 借出时间
ReturnDate Datetime, -- 归还时间
...
)
用到的功能有 :
1. 如果我更改了学生的学号 , 我希望他的借书记录仍然与这个学生相关 ( 也就是同时更改借书记录表的学号 );
2. 如果该学生已经毕业,我希望删除他的学号的同时,也删除它的借书记录。
等等。
这时候可以用到触发器。对于 1 ,创建一个 Update 触发器:
Create Trigger truStudent
On Student -- 在 Student 表中创建触发器
for Update -- 为什么事件触发
As -- 事件触发后所要做的事情
if Update (StudentID)
begin
Update BorrowRecord
Set StudentID=i.StudentID
From BorrowRecord br , Deleted d ,Inserted i --Deleted 和 Inserted 临时表 ,系统中自动存在的
Where br.StudentID=d.StudentID
end
理解触发器里面的两个临时的表: Deleted , Inserted 。注意 Deleted 与 Inserted 分别表示触发事件的表 “ 旧的一条记录 ” 和 “ 新的一条记录 ” 。
一个数据库系统中有两个虚拟表用于存储在表中记录改动的信息,分别是:
虚拟表 Inserted 虚拟表 Deleted
在表记录新增时 存放新增的记录 不存储记录
修改时 存放用来更新的新记录 存放更新前的记录
删除时 不存储记录 存放被删除的记录
一个 Update 的过程可以看作为:生成新的记录到 Inserted 表,复制旧的记录到 Deleted 表,然后删除 Student 记录并写入新纪录。
对于 2 ,创建一个 Delete 触发器
Create trigger delStudent
On Student
for Delete
As
Delete BorrowRecord
From BorrowRecord br , Deleted d
Where br.StudentID=d.StudentID
从这两个例子我们可以看到了触发器的关键: A.2 个临时的表; B. 触发机制