觸發器,就是制定一個規則,在我們做增刪改操作的時候,只要滿足該規則,自動觸發,無需調用。
- 語句級觸發器:不包含有for each row的觸發器;
- 行級觸發器:包含有for each row的觸發器。
加for each row是爲了使用 :old 對象或者 :new 對象(一行記錄),其含義如下表。
觸發語句 | :old | :new |
---|---|---|
insert | 所有字段都是空(null) | 將要插入的數據 |
update | 更新以前該行的值 | 更新後的值 |
delete | 刪除以前該行的值 | 所有字段都爲空(null) |
以scott用戶下的表爲例:
1. 語句級觸發器
-- 案例:插入一條記錄,輸出一個新員工入職
create or replace trigger t1
after
insert
on dept
declare
begin
dbms_output.put_line('一個新員工入職');
end;
-- 測試t1
select * from dept;
insert into dept values(50, 'Sss', 'Boston');
commit;
delete from dept where deptno=50;
2. 行級觸發器
-- 案例:不能給員工降薪
-- raise_application_error(-20001-20999之間, '錯誤提示信息');
create or replace trigger t2
before
update
on emp
for each row
declare
begin
IF :OLD.SAL>:NEW.SAL THEN
raise_application_error(-20001, '不能給員工降薪'); -- 拋出異常
END IF;
end;
-- 測試t2
select * from emp;
update emp set sal=sal-1 where empno=7782;