PL/SQL中触发器的简单使用
2012-03-22 12:58
344 查看
触发器的简单使用 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; 结果和以上的格式一样
相关文章推荐
- 简单触发器的使用 -- 献给SQL初学者
- Oracle(25)pl/sql编程 触发器及管理触发器及case...end case使用
- 使用pl/sql developer开发工具无法编译存储过程,触发器,包等程序文件
- 使用PL/SQl developer 增加自增字段和触发器
- PL/SQL创建简单的触发器trig…
- ORACLE PL/SQL循环简单使用
- [oracle编程]pl/sql --标量 复合变量以及游标的简单使用
- PL/SQL 第13章 使用触发器
- 第一博:Pl/Sql序列触发器的使用
- ORACLE数库之PL/SQL高级篇 存储过程,函数,包,触发器的使用
- PL/SQL简单使用——导入、导出数据表
- PL/SQL简单使用——导入、导出数据表
- PL/SQL Developer简单使用
- 简单触发器的使用 -- 献给SQL初学者
- 开发PL/SQL子程序和包及使用PL/SQL编写触发器、在JDBC中应用Oracle
- oracle 10g 学习之PL/SQL简介和简单使用(10)
- 2012年1月9日 星期一(oracle读书笔记,PL/SQL程序触发器的使用)
- [oracle编程]pl/sql --标量 复合变量以及游标的简单使用
- Oracle数据库编程:使用PL/SQL编写触发器
- PL/SQL 一个简单游标的使用