inserted,deleted是在触发器中使用的两个临时表,当执行insert操作时,在inserted中存储着当前插入的记录,在执行delete操作时,在deleted中存储着当前删除的记录,当执行update时,在inserted中存储着修改后的记录,在deleted中存储着修改前的记录。
建立触发器
- CREATE TRIGGER 触发器名称
- ON 表名
- { FOR | AFTER | INSTEAD OF }
- { [ INSERT ] [ , ] [ DELETE ] [ , ]
- [UPDATE ] }
- AS
- SQL 语句 [ ... n ]
删除触发器:
- DROP TRIGGER 触发器名 [ , ... n ]
- ALTER TRIGGER 触发器名称
- ON 表名
- { FOR | AFTER | INSTEAD OF }
- { [ INSERT ] [ , ] [ DELETE ] [ , ]
- [UPDATE ] }
- AS
- SQL 语句 [ ... n ]
开启和禁用:
- disable trigger trigDB on database --禁用触发器
- enable trigger trigDB on database --开启触发器
在S表创建UPDATE触发器:
- Create trigger tri_Updates
- on s
- for update
- as
- print 'the table s was updated'
禁止删除SC表中成绩不及格学生的记录:
- CREATE TRIGGER tri_del_grade
- ON SC FOR DELETE
- AS
- IF EXISTS(SELECT * FROM DELETED
- WHERE Grade < 60)
- ROLLBACK
禁止将SC表中不及格学生的成绩改为及格:
- create trigger tri_update_grade
- on sc for update
- as
- if update(grade)
- if exists(select * from inserted,deleted
- where inserted.sno=deleted.sno and inserted.grade>=60 and deleted.grade<60)
- begin
- print '不能将不及格的成绩改为及格'
- rollback
- end