触发器中的:NEW 和 :OLD的用法
触发器学习笔记(:new,:old用法) 触发器是 数据库发生某个操作时自动运行的一类的程序 用于保持数据的完整性或记录数据库操作信息方面 触发器不能够被直接调用,只能够在某些事件发生时被触发,也就是 系统自动进行调用触发器的构建语法 create [or replace] trigger trigger_name before|after event1 [ or event2 or event3 …] on table_name [for each row] begin statement; … end; 通常是insert、delete或update等DML操作 说明: For each row的意义是:在一次操作表的语句中,每操作成功一行就会触发一次;不写的 话,表示是表级触发器,则无论操作多少行,都只触发一次; When条件的出现说明了,在DML操作的时候也许一定会触发触发器,但是触发器不一定会做实际的工作,比如when 后的条件不为真的时候,触发器只是简单地跳过了PL/SQL块. 触发器分为语句级触发器和行级触发器 语句级触发器是指每执行一条DML语句,该触发器就执行一次 行级触发器是指每个DML操作影响几条记录,就会触发几次(for each row) 行级触发器中由于涉及到了每条记录的数据变动,所以对于每条记录的数据来说就有新值和旧值之分 (语句级触发器不能用old和new) 关键字: :NEW 和:OLD使用方法和意义,new 只出现在insert和update时,old只出现在update和delete时。在insert时new表示新插入的行数据,update时new表示要替换的新数据、old表示要被更改的原来的数据行,delete时old表示要被删除的数据。 示例(1) --记录操作数据库信息方面 --创建一个t_emp2_log表用于存储用户对emp2表所做的操作信息 create table t_emp2_log( t_id number(10) primary key, --编号 t_date date, --修改日期 t_user varchar2(20), --操作用户 action varchar(20) --该用户所做操作 ); --创建触发器t_emp2,当有用户对表emp2操作的时候,就会触发该触发器,记录改用户对表emp2所做的操作 create or replace trigger t_emp2 after update or delete or insert on emp2 begin if updating then --当执行更新操作时执行 insert into t_emp2_log values(seq_t_emp2_log.nextval,sysdate, user, 'update'); elsif deleting then --当执行删除操作时执行 insert into t_emp2_log values(seq_t_emp2_log.nextval,sysdate, user, 'delete'); elsif inserting then -- 当执行插入操作时 insert into t_emp2_log values(seq_t_emp2_log.nextval, sysdate, user, 'inserting'); end if; end; 示例(2) --保持数据的完整性... create table dept2 as select * from dept; --当存在依赖表时,当主表的信息发生改变时,依赖表的相应信息也会发生改变 create or replace trigger tr_emp2 --当主表dept2发生改变时, after update on dept2 for each row begin --依赖表也会发生相应的变化,以保持数据的完整性 update emp2 e set e.deptno = :NEW.deptno where e.deptno = :OLD.deptno; end; 示例 (3) 两个表 字段完全一样 例如:emp 表 emp_ copy 表 要求 :写一个触发器 提示: :NEW :OLD 功能实现 当往emp表内添加字段且deptno=10的时候 往emp_copy表copy此数据 在emp表更新数据时且修改deptno=10 的时候 往emp_copy表copy此数据 www.2cto.com --向emp_copy表copy新数据 --emp_copy可以存在相同的记录 create or replace trigger tr_emp_copy after insert or update on emp2 for each row begin if inserting then if :NEW.deptno = 10 or :OLD.deptno = 10 then insert into emp_copy values(:NEW.empno, :NEW.ename, :NEW.job, :NEW.mgr,:NEW.hiredate, :NEW.sal, :NEW.comm, :NEW.deptno); end if; elsif updating then if :OLD.deptno = 10 then insert into emp_copy values(:NEW.empno, :NEW.ename, :NEW.job, :NEW.mgr,:NEW.hiredate, :NEW.sal, :NEW.comm, :NEW.deptno); end if; end if; end; --注意事项 /* 不管是after ,还是 before 在update , insert , delete 时,一定是在事务提交之后才会触发触发器 before 和after的区别:before:insert update 可以对new进行修改。 after :不能对new 进行修改 二者都不能对old 进行修改 */ create or replace trigger tri_emp2 before update on dept2 for each row begin :NEW.deptno := 80; update emp2 e set e.deptno = :NEW.deptno where e.deptno = :OLD.deptno; end;
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
