數據庫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,可以用存儲過程來實現相應的功能。

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