您的位置:首页 > 数据库

PL/SQL中触发器的简单使用

2012-03-22 12:58 274 查看
触发器的简单使用
1.触发器介绍
数据库触发器是一个与表相关联的、存储的PL/SQL程序。每当一个特定的数据操作语句(Insert,update,delete)在指定的表上发出时,Oracle自动地执行触发器中定义的语句序列。

2.触发器的类型
(1)	语句级触发器
在指定的操作语句操作之前或之后执行一次,不管这条语句影响了多少行 。
(2)	行级触发器(FOR EACH ROW)
触发语句作用的每一条记录都被触发。在行级触发器中使用old和new伪记录变量, 识别值的状态。

3.触发器的举例
(1)限制非工作时间向数据库中插入数据
create or replace trigger insertEmp
before insert on emp
declare
begin
if(to_char(sysdate,'day') in ('星期四','星期五')) then
raise_application_error(-20001,'不能插入数据');
end if;
end;

测试:
SQL> insert into emp(empno,deptno) values(14,10);

insert into emp(empno,deptno) values(14,10)
ORA-20001: 不能插入数据
ORA-06512: 在 "TEST1.INSERTEMP", line 5
ORA-04088: 触发器 'TEST1.INSERTEMP' 执行过程中出错

(2)更改的数据不能小于原原有的值
create or replace trigger updateEmp
before update on emp
for each row
declare
-- local variables here
begin
if :new.sal< :old.sal then
raise_application_error(-20002,'更改的数据不能小于原原有的值');
end if;
end updateEmp;

测试:
SQL> update emp set sal=200 where empno=7369;

update emp set sal=200 where empno=7369

ORA-20002: 更改的数据不能小于原原有的值
ORA-06512: 在 "TEST1.UPDATEEMP", line 5
ORA-04088: 触发器 'TEST1.UPDATEEMP' 执行过程中出错

(3) 指定部门插入的员工数不能大于5
create or replace trigger limite
before insert on emp
for each row
declare
-- local variables here
cursor cl is select count(*) from emp group by deptno;
emp_count emp.empno%type;
begin
open cl;
fetch cl into emp_count;
if (emp_count>5) then
raise_application_error(-20002,'员工个数不能多余5个');
end if;
close cl;
end limite;

或
create or replace trigger limite
before insert on emp
for each row
declare
num number;
begin
select count(*) into num from emp where deptno=:new.deptno;
if(num>=5) then
raise_application_error(-20002,'员工个数不能多余5个');
end if;
end limite;

结果和以上的格式一样
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息