oracle笔记九(触发器)
触发器:
分类:
a).DML触发器
b).替代触发器
c).系统触发器
创建DML触发器:
Create or replace trigger Tri_DelEmp
Before delete on scott.emp
For each row
Begin
insert into emp_history(empno,ename,job,sal
,comm,hiredate,mgr,deptno)
values(:old.empno,:old.ename,:old.job,:old.sal,
:old.comm,:old.hiredate,:old.mgr,:old.deptno);
End;
create or replace trigger Tri_sal
before update or insert of sal on emp
referencing old oo new nn
for each row
begin
if :nn.sal>15000 and :nn.job<>'PRESIDENT' and :nn.job<>'MANAGER' then
dbms_output.put_line('not so many');
raise_application_error(-20010,'not so many');(-20000~-20999)
end if;
end;
触发器的限制:
? CREATE TRIGGER语句文本的字符长度不能超过32KB
? 触发器体内的SELECT 语句只能为SELECT … INTO …结构,或者为定义游标所使用的SELECT 语句
? 触发器中不能使用数据库事务控制语句 COMMIT, ROLLBACK, SVAEPOINT 语句
? 由触发器所调用的过程或函数也不能使用数据库事务控制语句
? 触发器中不能使用LONG, LONG RAW 类型
DML触发器中的谓词:
a). inserting 如果触发语句是INSERT,则为TRUE,否则为FALSE
b). updating 如果触发语句是UPDATE,则为TRUE,否则为FALSE
c). deleting 如果触发语句是DELETE,则为TRUE,否则为FALSE
create or replace trigger check_emp
before insert or update or delete on emp
for each row
begin
if inserting then
dbms_output.put_line('insert');
elsif updating then
dbms_output.put_line('update');
elsif deleting then
dbms_output.put_line('delete');
else
dbms_output.put_line('others');
end if;
end;
创建替代触发器:(替代触发器主要用于对复杂视图操作进行处理)
Create or replace trigger emp_view_del
Instead of delete on emp_view
For each row
Begin
delete from emp where deptno=:old.deptno;
End;
创建系统级触发器:
Create or replace trigger event_log_tri
After create or alter or drop on database(建立在整个数据库上,需要用DBA身份,可对所以user检测)
Begin
insert into logevent
values(sysevent,dictionary_obj_type,dictionary_obj_name,
dictionary_obj_owner);
End;
create or replace trigger logon_tri
after logon on schema(建立在方案上,即只对本user检测)
begin
insert into log
values(user,sysdate,'logon');
end;
触发器状态:
Alter trigger logno_tri disable/enable;
Alter table emp disable/enable all triggers;