数据库SQL(六):Triggers(触发器)

1、what are triggers

A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database. (insert, delete, update)
Also called event-condition-action rules (ECA).
A trigger allows the programmer to specify when the check occurs and under which conditions a set of actions should be performed.
A trigger allow applications to monitor database events (activities) and take actions when specified events take place.
To design a trigger mechanism, we must:
Specify the event causes the trigger and the conditions must be satisfied for trigger execution. (when a trigger is to be executed)
Specify the actions to be taken when the trigger executes.

也就是说,Trigger是一个语句,这个语句在满足一定条件时自动执行:当对数据库进行修改(增、删、改)时,记录的值满足特定条件时。Trigger也称为event-condition-action规则。
应用trigger可以使应用程序监控数据库的一些事件。
应用trigger时要做两项工作
1)说明什么条件下执行触发器:引起触发器的事件(event)和触发器执行必须满足的条件(condition);
2)触发器执行时触发的动作。

2、Example

在这里插入图片描述
这个例子介绍了trigger的定义。Trigger定义包括trigger的名字、触发的事件和条件以及执行的动作。
在这个例子中实现的功能是:当对section表进行insert操作时,如果增加的新的纪录的time_slot_id不在time_slot表中,那么这个这个insert操作无法成功执行,插入的数据要删掉,所有对数据库的操作rollback(回滚),恢复插入之前的数值。

这个trigger命名为timeslot_check1,事件是对数据库表section进行insert操作,trigger执行的条件是当插入section表的的新数据的time_slot_id不在time_slot表中时,由when语句指定。Trigger执行的操作时rollback。

注意:referencing new row as nrow这条语句,建立一个临时变量存储新增的数据;还有另一种方式referencing old row as orow,建立临时变量存储删掉或修改行的旧数据。as子句后是临时变量名,实际是一个临时表。

3、Triggering Events and Actions in SQL

Trigger有两个关键属性,event和action。
event是对数据库的修改操作:insert、delete和update,action根据数据管理需要完成语句。

Triggering event can be insert, delete or update;
Triggers on update can be restricted to attributes;
E.g., after update of takes on grade
Values of attributes before and after an update can be referenced
referencing old row as : for deletes and updates
referencing new row as : for inserts and updates

在这里插入图片描述

4、When Not To Use Triggers

写trigger时要特别小心,因为运行期间一个trigger错误会导致引发该trigger的action语句失败,而且一个trigger的动作可以引发另一个触发器,最坏情况下,会导致一个无限的触发链。

【注意】如果有其他替代方法最好不用trigger,可以用存储过程来实现相应的功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章