面试题之触发器

一、 什么是触发器?

数据库触发器是一个与表相关联的、存储的PL/SQL程序

  • 每当一个特定的数据操作语句(insert,update,delete)在指定的表上发出时,就是执行触发器中定义的语句序列。
create trigger first_trigger

after insert

on emp

begin

dbms_output.put_line("新增成功");

end;

/

二、 应用场景

  • a. 复杂的安全检查
  • b. 数据的确认
  • c. 数据库的审计
  • d. 数据库的备份与同步

三、触发器的分类

a. 语句级触发器:针对的是表

b. 行级触发器:针对的是行【for each row】

四、案例

【a】触发器案例一:禁止在非工作时间插入新员工信息【实施安全性检查】

create or replace trigger security_check

before insert on emp

begin

if to_char(sysdate,'day') in ('星期六','星期日') or

to_number(to_char(sysdate,'hh24')) not between in 9 and 18

raise_application_errors(-20001,'禁止在非工作时间插入新员工')

end if;

end;

/

【b】触发器案例二:涨工资之后的工资一定要大于涨之前的工资【数据的确认】

create or replace trigger check_salary

before update on emp for each row

begin

if :now.sal > :old.sal

raise_application_error(-20002,'涨后的工资不能少于涨钱的工资')

end if;

end;

/

【c】触发器案例三:当涨完工资大于6000的时候审计信息【数据库的审计】

create or replace check_sal

after update

on emp for each row

begin

if :new.sal > 6000 then

insert into info values("姓名:"||:new.ename || "涨后的工资:" || :new.sal)

end if;

end;

/

【d】 触发器案例四: 备份从表的数据【数据库的备份与同步】

create or replace asyc_record

after update on emp for each row

begin

update emp_back set sal = :new.sal where empno = :new.empno;

end;

/
发布了220 篇原创文章 · 获赞 93 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/Weixiaohuai/article/details/104157307