Oracle触发器和new、old特殊变量

:new --为一个引用最新的列值;
:old --为一个引用以前的列值;

这两个变量只有在使用了关键字 "FOR EACH ROW"时才存在.且update语句两个都有,而insert只有:new ,delect 只有:old;

系统中的触发器实例:

createor replace trigger JBPM.TIB_DEPLOYBYMOVEPAPER

  before//before表示在操作完成前触发,after表示在完成后触发

  insert//发生插入数据操作触发 OR UPDATE OR DELETE

  on JBPM.DEPLOYBYMOVEPAPER

for each row //指定触发器每行触发一次

declare
    integrity_error exception; //用户自定义错误
    errno           integer;
    errmsg           char(200);
    dummy           integer;
    found           boolean;
    row_count number;
    max_num deploybymovepaper.num%type; //根据表的字段定义变量类型
    zero_today deploybymovepaper.num%type;

 

begin
      -- Column "ID" uses sequence SEQUENCE_38
      case when inserting then //SQL语句只能使用:new特殊变量

        select SEQUENCE_38.NEXTVAL INTO :new.ID from dual;//主键自增

        zero_today :='0391'||to_char(sysdate,'yymmdd')||lpad(to_char(0),4,'0');//lpad函数定义字符串长度为4不足时用0补全

        select count(*) into row_count from deploybymovepaper;

    if row_count = 0 then
        max_num:=zero_today;//:=给变量赋值
    else
      select max(num) into max_num from deploybymovepaper;
    end if;

    if max_num<zero_today then
        max_num:=zero_today;
    end if;
    if :new.num is null then
    :new.num:=lpad(to_char(to_number(max_num)+1),14,'0'); //递增编号,有14为数字组成
    end if;

     when updating then//:new、:old都可以用
        if :new.num!=:old.num then
           :new.num:=:old.num;
        end if;
     end case;

-- Errors handling
exception
    when integrity_error then
       raise_application_error(errno, errmsg); //抛出异常语句
end;

--异常处理:http://blog.csdn.net/pan_tian/article/details/7492653


--拿当前数据 :new.para作为条件,再次对触发的表进行操作时出错

在于过程中用:new.para再次去查目标表,这一动作被oracle认为是不合法的。

目标表的记录行如果做了更新,无需再通过ID去查询目标记录行。这一动作被oracle认为是不合法的。

如果想进行查询,可以在触发器的declare上加上

pragma autonomous_transaction;

--自治事务:http://blog.itpub.net/26110315/viewspace-729971/


 

查看某个表的触发器

select   *  from   all_triggers
where   table_name   =upper( 'tbname ')


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值