oracle学习(九)触发器

触发器:与表相关联的PLSQL语句,当我们对数据库中的表进行增删改时,会自动执行的PLSQL。

语法:

create or replace trigger 触发器名
-- 此处为设置在插入操作前
before insert
-- 在哪张表上
on emp
-- 可选项
-- 触发器分为语句级触发器,行级触发器
-- 标志就是下面一句,行级触发器需要带上下面一句
【for eachrow where 条件】
begin
   语句
end;
/

触发器分为语句级触发器,行级触发器

语句级: 针对表,对这张表操作就触发,而不论影响多少行

行级:针对表中的行,影响一行就触发一次。用:old   和:new识别值的状态

语句级触发器demo

/*
触发器应用一:实施复杂的安全性检查
禁止在非工作时间插入新员工

1. 周末:to_char(sysdate,'day') in ('星期六','星期日')
2. 上班前 下班后:to_number(to_char(sysdate,'hh24')) not between 9 and 18
*/
create or replace trigger securityemp
before insert
on emp
begin
  if to_char(sysdate,'day') in ('星期六','星期日') or 
     to_number(to_char(sysdate,'hh24')) not between 9 and 18 then
     --禁止insert
     raise_application_error(-20001,'禁止在非工作时间插入新员工');
     
  end if;
end;
/

行级触发器demo

/*
数据的 确认: 涨后的工资不能少于涨前的工资
*/
create or replace trigger checksalary
before update
on emp
for each row 
begin

  --if 涨后的薪水  < 涨前的薪水  then
  if :new.sal < :old.sal then
      raise_application_error(-20002,'涨后的工资不能少于涨前的工资。涨前:'||:old.sal||'  涨后:'||:new.sal);
  end if;

end;
/

猜你喜欢

转载自blog.csdn.net/quge_name_harder/article/details/88073664