Oracle 触发器两表同步

触发器无需commit
也不能写commit
触发器和触发它的DML是同一个事务
DML提交了,触发器的操作也提交了,要不就一起回滚了

当然,如果你一定要在触发器里写COMMIT
那就用自治事务
相当于一个事务里的子事务

正常情况下,Oracle规定在触发器中不能运行 ddl语句和commit,rollback语句。

解决办法有两种:

1.在可以在触发器中加入:pragma autonomous_transaction; 表示自由事务处理。
如:

CREATE OR REPLACE TRIGGER T_create BEFORE insert ON T_RCatalogue
for each row
DECLARE
pragma autonomous_transaction;

NRDSId varchar(500):='';

begin

2.可以另外写一个方法,把dll语句传递到这个方法中去执行。

注释:
   ddl语句:DDL语句用语定义和管理数据库中的对象,如Create,Alter,Drop,truncate等;DDL操作是隐性提交的!操作立即生效,原数据不放到rollback segment中,不能回滚. 操作不触发trigger
   DML(Data Manipulation Language)数据操纵语言命令使用户能够查询数据库以及操作已有数据库中的数据。如insert,delete,update,select等都是DML.

-======================================================================

建表:

create table User_Info (

   ID                   INTEGER                         not null,

   UserName            VARCHAR(30)                     not null,

   PassWord            VARCHAR(20)                     not null,

   CreateDate          Date                            not null,

   Status              INTEGER                         not null,

   constraint PK_User_Info primary key (ID)

);

create table User_Info_temp (

   ID                   INTEGER                         not null,

   UserName            VARCHAR(30)                     not null,

   PassWord            VARCHAR(20)                     not null,

   CreateDate          Date                            not null,

   Status              INTEGER                         not null,

   constraint PK_User_Info_temp primary key (ID)

);

触发器写法:

create or replace trigger UserToTemp after insert or update or delete

on user_info for each row

declare

    integrity_error exception;

    errno            integer;

    errmsg           char(200);

    dummy            integer;

    found            boolean;

begin

if inserting then

    insert into User_info_temp(ID,UserName,PassWord,CreateDate,Status) values(:NEW.ID,:NEW.UserName,:NEW.PassWord,:new.CreateDate,:NEW.Status);

elsif updating then

    update User_info_temp set ID=:NEW.ID,UserName=:NEW.UserName,PassWord=:NEW.PassWord,Status=:NEW.Status where id=:OLD.id;

elsif deleting then

    delete from User_info_temp where id=:OLD.id;

end if;

exception

    when integrity_error then

       raise_application_error(errno, errmsg);

end;

测试数据:

insert into user_info(ID,UserName,PassWord,CreateDate,Status)values(1,'xier','222',to_date('2008-10-11','yyyy-mm-dd'),1)

update user_info u set u.status=3,u.username='xier' where u.id=1

delete from user_info u where u.id=1

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值