触发器

来源:互联网 发布:爱名网域名过户步骤 编辑:程序博客网 时间:2024/06/08 02:26

触发器

     数据库触发器是一个与表相关的 存储PL/SQL程序 每当一个特定的数据库操作语句insert updatedelete 在指定的表上发出时oracle自动地执行触发器中定义的语句序列

 

触发器类型

 语句级触发

        在指定的操作语句操作之前或之后执行一次 不管这条语句影响了多少行

 行级触发 FOR  EACH ROW

     触发器语句作用的每一条记录都被触发 在行级触发中使用:old和:new 伪记录变量 识别值的状态

 

/*

插入一条记录后 自动打印 成功插入一个员工

*/

create or replace trigger firsTrigger

after insert

on emp

begin

dbms_output.put_line('成功插入一个员工');

end;

/

 

触发器可用于

  数据确认

  实施复杂的安全性检查

  做审计 跟踪表上所做的数据操作等

  数据的备份和同步

 

查询触发器 过程及函数

Select * from usertriggers;

Select * from user_source;

 

 

触发器的语法:

CREATE [OR REPLACE] TRIGGER 触发器名{before|after}

{delete|insert|update[of列名]}

On 表名

[for each row[when(条件)]]

Plsql块

 


/*

实施复杂的安全性检查

限制非工作时间向数据库插入数据

*/

--周末to_char(sysdate,'day') in ('星期六','星期天')

--上班前 下班后to_number(to_char(sysdate,'hh24'))not between 9 and 18

create or replace triggersecurityEmp

before insert

on emp

begin

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

or

to_number(to_char(sysdate,'hh24'))notbetween 9 and 18 then

raise_application_error(-20001,'不能再非工作时间内操作数据库!');

end if;

end;

/

insert intoemp(empno,ename,deptno)values(1001,'tom',10);

 

 

/*

确认数据 (涨后的薪水不能少于涨前的薪水)

*/

 

create or replace triggerchechsal

before update

on emp

for each row

begin

if :new.sal < :old.sal then

raise_application_error(-20001,'涨后的薪水不能小于涨前薪水,涨前:'||:old.sal||'涨后:'||:new.sal);

end if;

end;

/

update emp set sal=sal-1 whereempno=7839;

 

1.     练习:限制每个部门只招聘5名职工,超过计划则报出错误报告  

2.     构建触发器  

3.     create or replace trigger insertEmp  

4.       before insert on emp    

5.       for each row  

6.     declare  

7.       -- local variables here  

8.       cursor c1 is select count(*) from emp group by deptno;  

9.       count1 number;  

10. begin  

11.    open c1;  

12.   fetch c1 into count1;  

13.     if   

14.      count1>=5  

15.     then  

16.      raise_application_error(-20003,'本部门不能再插入了');  

17.     end if;  

18.      

19.     --  dbms_output.put_line(count1);  

20.     close c1;  

21.  end insertEmp;

 

create table test1(

id number primary key,

name varchar2(20),

money number

);

 

insert into test1values(1,'TOM',1000);

insert into test1values(2,'Mary',2000);

insert into test1values(3,'Mike',3000);

insert into test1values(4,'Jeff',4000);

commit;

select * from test1;


原创粉丝点击