触发器,就是制定一个规则,在我们做增删改操作的时候,只要满足该规则,自动触发,无需调用。
- 语句级触发器:不包含有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;