码迷,mamicode.com
首页 > 数据库 > 详细

oracle 触发器的使用

时间:2017-04-23 15:55:13      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:sda   replace   ora   table   for   工作   int   rom   var   

触发器的格式

create or replace trigger   触发器的名字

before [after]    insert[update,delete]

on  作用于哪张表

[for each row]     如果是语句级触发器就不用写,行级触发器要写

declare

begin

end;

 

--触发器的使用场景一 复杂的安全检查
--案例一 禁止在非工作时间添加员工数据
create or replace trigger securityemp
before insert
on emp
declare
begin
if to_char(sysdate,‘day‘)in(‘星期六‘,‘星期日‘) or
to_number(to_char(sysdate,‘hh24‘)) not between 9 and 18 then
raise_application_error(-20001,‘禁止在非工作时间插入新员工‘);
end if;
end;
--测试
insert into emp(ename) values (‘你好‘);
--触发器的使用场景二 数据的确认
--场景 涨后的工作不能少于涨前的工资
create or replace trigger cheaksalary
before update
on emp
for each row
declare
begin
if :new.sal < :old.sal then
raise_application_error(-20002,‘涨后的薪水不能少于涨前的薪水,涨前薪水:‘||:old.sal||‘涨后的薪水:‘||:new.sal);
end if;
end;
--测试
update emp set sal=sal-11 where empno=7788;
--触发器的使用场景三 数据库的审计 基于值的审计
--场景 审计涨后工资超过5000的员工

create table audit_info( --建立一个新的表 用于检验工资超过5000的员工
information varchar2(200)
);

create or replace trigger do_autit_emp_salary
after update
on emp
for each row
declare
begin
if :new.sal>6000 then
insert into audit_info values (:new.deptno||‘ ‘||:new.ename||‘ ‘||:new.sal);
end if;
end;
--检测
update emp set sal=sal+2000;
select *from emp;
select * from audit_info;


--触发器的使用场景四 数据库的备份和同步
--场景 emp1中工资修改后 同步到copy_emp1中

create or replace trigger copy_emp1
after update
on emp1
for each row
declare
begin
update emp_back set sal=:new.sal where empno=:new.empno;
end;

--检测

update emp1 set sal=sal+100 where empno=7788;
select * from emp1 where empno=7788;
select * from emp_back where empno=7788;

oracle 触发器的使用

标签:sda   replace   ora   table   for   工作   int   rom   var   

原文地址:http://www.cnblogs.com/yin-dt/p/6752585.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!