1 觸發器
數據庫觸發器是一個與表相關聯、存儲的PL/SQL程序。每當一個特定的數據操作語句(Insert,Update,delete)在指定的表上發出時,Oracle自動地執行觸發器中定義的語句序列。
觸發器的類型
- 語句級觸發器
在指定的操作語句操作之前或之後執行一次,不管這條語句影響了多少行。 - 行級觸發器(FOR EACH ROW)
觸發語句作用的每一條記錄都被觸發。在行級觸發器使用:old和:new 僞記錄變量,識別值的狀態
1.1 語法格式
CREATE [or REPLACE] TRIGGER 觸發器名
{BEFORE | ALTER}
{DELETE | INSERT | UPDATE [OF 列名]}
ON 表名
[FOR EACH ROW [WHEN(條件)]]
PLSQL 塊
1.2 案例
插入員工後打印一句輸出
create trigger abcd after insert on emp
declare
begin
DBMS_OUTPUT.PUT_LINE('成功插入新員工');
end;
set serveroutput on
insert into emp (empno,ename,sal,deptno) values(1122,'zhangsan',1920,10);
實施複雜的安全性檢查 禁止在非工作時間插入新員工
create trigger securityemp before insert on emp
begin
if to_char(sysdate,'day') in ('星期六','星期日') or
to_number(to_char(sysdate,'hh24')) not between 9 and 17
then RAISE_APPLICATION_ERROR(-20001, '禁止非工作時間插入新員工');
end if;
end;
set serveroutput on
insert into emp (empno,ename,sal,deptno) values(1432,'zhangsan3',1920,10);
commit;
漲後的工資不能少於漲前的工資
create or replace trigger checksalary
before update
on emp
for each row
begin
if :new.sal < :old.sal then
raise_application_error(-20002,'漲後的工資不能少於漲前的工資new:'||:new.sal||' old:'||:old.sal);
end if;
end;
set serveroutput on;
update emp set sal = sal -10 where empno=1122;