同一数据库不同用户的两张表双向同步--触发器+包

1.新建package(A用户中)
create or replace package pk_check_active is
  --标识是否为触发器引发
  n number :=0;
  --获取是否为触发器触发标识,1为触发器触发
  function getactive return number;
  --设置状态
  procedure setactive(n1 in number);
end pk_check_active;
2.新建packageBody(A用户中)
create or replace package body pk_check_active as


  function getactive return number is
  begin
    return n;
  end getactive;
  procedure setactive(n1 in number) is
  begin
    n := n1;
  end setactive;
end pk_check_active;
3.A触发器
create or replace trigger tri_A
  after DELETE OR INSERT OR UPDATE on tableNameA
  for each row
declare
  -- local variables here
begin
  if pk_check_active.getactive() =1 then
     pk_check_active.setactive(0);  return;
  else
     pk_check_active._setactive(1);
  end if;
  IF INSERTING THEN
    --INSERT触发
    INSERT INTO B.tableNameB 
     VALUES
      (SYS_GUID(),
       :NEW.FILENAME,
       :NEW.FILEPATH,
       :NEW.FILESIZE,
       '7',
       :NEW.OBJID,
       '1');
  ELSIF UPDATING THEN
       update B.tableNameB 
         set IMAGE_NAME   = :NEW.FILENAME,
             IMAGE_PATH   = :NEW.FILEPATH,
             MEMO         = :NEW.FILESIZE
       where BUSINESS_ID = :NEW.OBJID and BUSINESS_TYPE='7';
  ELSIF DELETING THEN
    --DELETE触发
    delete from B.tableNameB where BUSINESS_ID = :OLD.OBJID and BUSINESS_TYPE='7';
  END IF;
end tri_A;
4.相互授权(已授权此步骤可跳过)
A:


grant execute on PK_CHECK_ACTIVE to B;


GRANT SELECT ON tableNameA TO B;
GRANT INSERT ON tableNameA TO B;
GRANT UPDATE ON tableNameA TO B;
GRANT DELETE ON tableNameA TO B;
B:
GRANT SELECT ON tableNameB TO A;
GRANT INSERT ON tableNameB TO A;
GRANT UPDATE ON tableNameB TO A;
GRANT DELETE ON tableNameB TO A;
5.定义(私有)同义词(B用户中)
create synonym PK_CHECK_ACTIVE for A.PK_CHECK_ACTIVE;
6.B触发器
create or replace trigger tri_image_B
  after DELETE OR INSERT OR UPDATE on tableNameB 
  for each row
declare
  -- local variables here
begin
  if pk_check_active_img.getactive() =1 then


     pk_check_active_img.setactive(0);  return;
  else
     pk_check_active_img.setactive(1);
  end if;
  IF INSERTING THEN
    --INSERT触发
      INSERT INTO A.tableNameA 
      VALUES
        (:NEW.BUSINESS_ID,
         :NEW.IMAGE_NAME,
         null,
         :NEW.IMAGE_PATH,
         decode(:NEW.MEMO,null,null,to_number(:NEW.MEMO)),
         null);
  ELSIF UPDATING THEN
       update A.tableNameA 
         set FILENAME          = :NEW.IMAGE_NAME,
             FILEPATH          = :NEW.IMAGE_PATH,
             FILESIZE          = decode(:NEW.MEMO,null,null,to_number(:NEW.MEMO))
       where OBJID = :NEW.BUSINESS_ID;
  ELSIF DELETING THEN
    --DELETE触发
       delete from A.tableNameA where OBJID = :OLD.BUSINESS_ID;
  END IF;
end tri_image_B;

你可能感兴趣的:(同一数据库不同用户的两张表双向同步--触发器+包)