觸發器是已知的存儲程序,自動執行,甚至在某些事件發生時觸發。在響應下列事件時,觸發器被執行。觸發器定義在事件關聯的表、視圖、模式或數據庫上。
- 數據庫操作(DML)語句(DELETE, INSERT或UPDATE)
- 數據庫定義(DDL)語句(CREATE、ALTER或DROP)
- 一個數據庫操作(SERVERERROR, LOGON, LOGOFF, STARTUP, SHUTDOWN)
創建觸發器:語法:CREATE [OR REPLACE] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF} {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [reference OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) DECLARE DECLARE -statements BEGIN Executable-statements EXCEPTION異常處理-statements END;
在那裏,
- CREATE [OR REPLACE] TRIGGER trigger_name—用給定的trigger_name創建或替換現有的觸發器。
- {BEFORE | AFTER | INSTEAD OF} -指定何時執行觸發器。INSTEAD OF子句可用於在視圖上創建觸發器。
- {INSERT [OR] | UPDATE [OR] | DELETE} -它指定DML操作。
- [OF col_name] -它指定要更新的列名。
- [ON table_name]−與觸發器相關聯的表名。
- [引用舊AS o新AS n]−這允許我們為各種DML語句引用新的和舊的值,如INSERT, UPDATE和DELETE。
- [FOR EACH ROW]—指定一個行級觸發器。
示例:從客戶中選擇*;參考我們在函數部分中創建的表:CREATE OR REPLACE TRIGGER display_salary_changes BEFORE DELETE OR INSERT OR UPDATE ON teachers FOR EACH ROW WHEN (NEW。ID > 0) DECLARE sal_diff number;開始sal_diff:=:NEW。salary -:OLD.salary;dbms_output。put_line('舊工資:' ||:老工資);dbms_output。put_line('New salary: ' ||: New .salary);dbms_output。put_line('工資差異:' || sal_diff);結束; /
輸出:已創建觸發器。觸發觸發器:INSERT INTO TEACHERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (1, 'Ranjitha', 34, 'bangalore', 3500.00);顯示salary_changes;原工資:新工資:3500工資差值: