表t1和t1_temp有同样的结构和数据:create table t1 as select * from emp where 1=0;create table t1_temp as select * from emp where 1=0;alter table t1 add......
表t1和t1_temp有同样的结构和数据:
create table t1 as select * from emp where 1=0;
create table t1_temp as select * from emp where 1=0;
alter table t1 add constraint pk_empno1 primary key (empno);
alter table t1_temp add constraint pk_empno2 primary key (empno);
把表t1的操作同步到表t1_temp,触发器脚本如下:
create or replace trigger tgr_t1
after insert or update or delete on t1
for each row
begin
if :new.empno!=:old.empno
then
raise_application_error(-20001,'con not modify primary key');
end if;
if (inserting)
then
insert into t1_temp
values (:new.EMPNO,
:new.ENAME,
:new.JOB,
:new.MGR,
:new.HIREDATE,
:new.SAL,
:new.COMM,
:new.DEPTNO);
end if;
if (deleting)
then
delete t1_temp
where empno=:old.empno;
end if;
if (updating)
then
update t1_temp
set
ENAME=:new.ENAME,
JOB=:new.JOB,
MGR=:new.MGR,
HIREDATE=:new.HIREDATE,
SAL=:new.SAL,
COMM=:new.COMM,
DEPTNO=:new.DEPTNO
where EMPNO=:old.EMPNO;
end if;
end;
在这里假设不能修改被同步表的主键(主要是为了同步简单),如果要修改主键,可以拆分成两条(一是主键删除,另一是主键插入)。
以上触发器是个简单的样本,实际工作中可能要比这复杂的多,可以根据需要增加功能。
下面验证正确性。
SQL> select * from t1;
no rows selected
SQL> select * from t1_temp;
no rows selected
SQL> insert into t1 select * from emp;
14 rows created.
SQL> commit;
Commit complete.
SQL> select * from t1;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- ------------ ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
1/5 1 2 3 4 5 下一页 尾页 |