oracle triggers 实现两个结构相同的表的数据级联更新操作

首先创建两个结构相同的表

-- Create table
create table TABLE_TEMP
(
  userid     NUMBER not null,
  username   NVARCHAR2(50),
  userno     NVARCHAR2(60),
  cardid     NVARCHAR2(18),
  createdate DATE,
  redate     DATE,
  month      VARCHAR2(6),
  amount     NUMBER
)
tablespace USERS
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 16
    next 8
    minextents 1
    maxextents unlimited
  );

 第二个表结构

-- Create table
create table TEST_TABLE_TEMP
(
  userid     NUMBER not null,
  username   NVARCHAR2(50),
  userno     NVARCHAR2(60),
  cardid     NVARCHAR2(18),
  createdate DATE,
  redate     DATE,
  month      VARCHAR2(6),
  amount     NUMBER
)
tablespace USERS
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 16
    next 8
    minextents 1
    maxextents unlimited
  );

 其中这两个表的ID都是不能自动增长的属性 没有建立sequences 序列以及自动增长的触发器

建立触发器:

create or replace trigger triggers_table_tempToTemp
before insert or update or delete
on table_temp for each row
declare
    integrity_error exception;
    errno            integer;
    errmsg           char(200);
    dummy            integer;
    found            boolean;

begin
 
if inserting then
    insert into test_table_temp(userid,UserName,userno,cardid,createdate,redate,month,amount)
     values(:NEW.userid,:NEW.UserName,:NEW.userno,:new.cardid,:NEW.createdate,:NEW.redate,:NEW.month,:NEW.amount);
elsif updating then
    update test_table_temp set userid=:NEW.userid,
    UserName=:NEW.UserName,userno=:NEW.userno,
    cardid=:NEW.cardid ,createdate=:NEW.createdate,
    redate=:NEW.redate,
    month=:NEW.month,
   amount=:NEW.amount
    where USERID=:OLD.USERID;
elsif deleting then
    delete from test_table_temp where userid=:OLD.userid;
end if;
exception
    when integrity_error then
       raise_application_error(errno, errmsg);
end;
--执行报错,错误信息:ORA-04084 无法更改此触发器类型的NEW值
--把触发器的after改成before 触发
--实现数据增删改 同时实现两个数据表同步信息

 测试数据

insert into TABLE_temp(userid,USERNAME,USERNO,CARDID,CREATEDATE,REDATE,MONTH,AMOUNT)
values('1','小晴','20140408','201404087976',to_date('2014-04-08','yyyy-mm-dd'),to_date('2014-04-08','yyyy-mm-dd'),'201404','100000')

update TABLE_temp set USERNAME='小清新' where userid=1
delete from TABLE_temp where userid=1

数据库中把一个表中的数据复制到另一个表中 如果不用其他方法直接用SQL语句实现:

1、如果是整个表复制如下:
insert into table1 select  * from table2
2、如果是有选择性的复制数据如下:
insert into table1(column1,column2,column3...) select column1,column2,colunm3... from table2
3、一个数据库中的表中的数据复制到另一个数据库中的一个表,使用方法如下:
insert into 数据库A.dbo.table1(col1,col2,col3...) select col1,col2,col3... from 数据库B.dbo.table2

 

posted @ 2014-04-08 18:06  蜜雪粮液  阅读(1439)  评论(0编辑  收藏  举报