- --创建一个插入操作的触发器:当向学生选课表SC中插入一条记录后,变更在学生表STUDENT对应学生的选课门数。
- CREATE TRIGGER STU_IN
- ON SC---对哪个表或者视图进行操作
- FOR INSERT--设定触发条件,也就是在什么情况下会触发这个触发器
- AS
- UPDATE STUDENT
- SET SCNUM = SCNUM +1
- FROM STUDENT INNER JOIN SC
- ON STUDENT.SNO = SC.SNO
- set statistics io on
- set nocount on
- insert into sc values('990001','001','99')
- delete from sc where sno='990001' and cno='001'
- --创建update触发器
- CREATE TRIGGER STU_UP
- ON STUDENT
- FOR UPDATE
- AS
- IF UPDATE(SNO)
- BEGIN
- RAISERROR('不能对SNO字段进行更新',10,1)
- ROLLBACK TRANSACTION
- END
- UPDATE STUDENT
- SET SNO='990032'
- WHERE SNO='990001'
- --创建delete触发器
- CREATE TRIGGER STU_DEL
- ON STUDENT
- FOR DELETE
- AS
- DELETE
- FROM SC
- WHERE SC.SNO IN(SELECT SNO FROM DELETED)
- exec sp_helptext stu_in--查看已经创建好的触发器的创建语句
- CREATE TRIGGER COM_UP
- ON COMPUTER
- INSTEAD OF UPDATE--INSTEAD OF主要用于对视图进行更新
- AS
- IF UPDATE(SNAME)------------------这个SNAME的值来自于输入update语句中的set后面的条件值
- BEGIN
- UPDATE STUDENT
- SET SNAME=INSERTED.SNAME
- FROM STUDENT INNER JOIN INSERTED
- ON STUDENT.SNO=INSERTED.SNO
- END
- ELSE
- BEGIN
- UPDATE SC
- SET CNO=INSERTED.CNO,
- GRADE=INSERTED.GRADE
- FROM SC INNER JOIN INSERTED
- ON SC.SNO=INSERTED.SNO
- END
- UPDATE COMPUTER
- SET GRADE=95
- WHERE SNO='990028'
- UPDATE COMPUTER
- SET SNAME='王晓晓'-------------------与IF UPDATE(SNAME)中的SNAME相对应
- where SNO='990028'
- SELECT * FROM COMPUTER
定义
触发器(trigger)是个特殊的存储过程,它的执行不是由程序调用,也不是手工启动,而是由事件来触发,比如当对一个表进行操作( insert,delete, update)时就会激活它执行。触发器经常用于加强数据的完整性约束和业务规则等。 触发器可以从 DBA_TRIGGERS ,USER_TRIGGERS 数据字典中查到。
实例