使用触发器在Oracle数据库中进行备份

时间:2018-07-25 21:49:00

标签: sql database oracle plsql triggers

我有2个相同的表,只需更改名称table1和table2,当在table1中输入3条记录时,该表的信息必须复制到表2,并且表1必须再次为空。

CREATE TABLE TABLA1(
ID_1 NUMBER PRIMARY KEY, NOMBRE VARCHAR2(40));

CREATE TABLE TABLA2(
ID_1 NUMBER PRIMARY KEY, NOMBRE VARCHAR2(40));

SELECT * FROM TABLA1;
SELECT * FROM TABLA2;


SET SERVEROUTPUT ON;
CREATE OR REPLACE TRIGGER DISP_BACKUP
BEFORE INSERT ON TABLA1
FOR EACH ROW
DECLARE
CURSOR CUR_CUENTA IS SELECT * FROM TABLA1;
--CURSOR CUR_CUENTA IS SELECT COUNT(*) FROM TABLA1;
var_rows := SQL%ROWCOUNT;
--CURCHOISE SQL%ROWCOUNT;
BEGIN
dbms_output.put_line('NUMERO DE REGISTROS EN TABLA 1' || CUR_CUENTA%ROWCOUNT 
);
--OPEN CUR_CUENTA;
IF CUR_CUENTA%ROWCOUNT > 3 THEN
IF INSERTING THEN
INSERT INTO TABLA2 (ID_1,NOMBRE) VALUES (:NEW.ID_1,:NEW.NOMBRE);
END IF;
DELETE FROM TABLA1;
END IF;
END;
/

1 个答案:

答案 0 :(得分:0)

您将需要使用语句触发器而不是行触发器-否则您将无法访问定义触发器的表。您可能还想使用AFTER INSERT而不是BEFORE INSERT触发器:

CREATE OR REPLACE TRIGGER DISP_BACKUP
  AFTER INSERT ON TABLA1
DECLARE
  TYPE typRowIDCollection IS TABLE OF ROWID;

  colROWIDs   typRowIDCollection;
BEGIN
  SELECT ROWID
    BULK COLLECT INTO colROWIDs
    FROM TABLA1;

  dbms_output.put_line('NUMERO DE REGISTROS EN TABLA 1' || colROWIDs.COUNT);

  IF colROWIDs.COUNT >= 3 THEN
    FORALL i IN colROWIDs.FIRST..colROWIDs.LAST
      INSERT INTO TABLA2 (ID_1, NOMBRE)
        SELECT ID_1, NOMBRE
          FROM TABLA1
          WHERE ROWID = colROWIDs(i);

    FORALL i IN colROWIDs.FIRST..colROWIDs.LAST 
      DELETE FROM TABLA1 WHERE ROWID = colROWIDS(i);
  END IF;
END DISP_BACKUP;

应该这样做。