oracle增量指令碼(記錄)建立觸發器監控對一張表的增刪改
刪除表
drop table test_1;
drop table test_1_log;
drop table A1;
drop table B1;
drop table C1;
–建立測試表
CREATE TABLE test_1(
t_id NUMBER(4),
t_name VARCHAR2(20),
t_age NUMBER(2),
t_sex CHAR
);
–建立記錄測試表
CREATE TABLE test_1_log(
l_user VARCHAR2(15),
l_type VARCHAR2(15),
l_date VARCHAR2(30)
);
–建立記錄新產生資料記錄表a1
create table a1 (
T_ID NUMBER(4),
TYPE CHAR,
TIME VARCHAR2(30)
);
–建立記錄新產生資料記錄表b1
create table b1 (
T_ID NUMBER(4),
TYPE CHAR,
TIME VARCHAR2(30)
);
–建立記錄新產生資料記錄表c1
create table c1 (
T_ID NUMBER(4),
TYPE CHAR,
TIME VARCHAR2(30)
);
建立觸發器
CREATE OR REPLACE TRIGGER test_1_TRIGGER
AFTER DELETE OR INSERT OR UPDATE ON test_1
FOR EACH ROW
DECLARE
V_TYPE test_1_LOG.L_TYPE%TYPE;
BEGIN
IF INSERTING THEN
–INSERT觸發
V_TYPE := ‘I’;
INSERT INTO A1 VALUES (:NEW.T_ID,‘I’,TO_CHAR(SYSDATE, ‘yyyy-mm-dd hh24:mi:ss’));
DBMS_OUTPUT.PUT_LINE(‘記錄已經成功插入,並已記錄到日誌’);
ELSIF UPDATING THEN
–UPDATE觸發
V_TYPE := ‘U’;
INSERT INTO B1 VALUES (:NEW.T_ID,‘U’,TO_CHAR(SYSDATE, ‘yyyy-mm-dd hh24:mi:ss’));
DBMS_OUTPUT.PUT_LINE(‘記錄已經成功更新,並已記錄到日誌’);
ELSIF DELETING THEN
–DELETE觸發
V_TYPE := ‘D’;
INSERT INTO C1 VALUES (:OLD.T_ID,‘D’,TO_CHAR(SYSDATE, ‘yyyy-mm-dd hh24:mi:ss’));
DBMS_OUTPUT.PUT_LINE(‘記錄已經成功刪除,並已記錄到日誌’);
END IF;
INSERT INTO test_1_LOG VALUES (USER, V_TYPE, TO_CHAR(SYSDATE, ‘yyyy-mm-dd hh24:mi:ss’));
–USER表示當前使用者名稱
END;
/
–測試
INSERT INTO test_1 VALUES(10,‘zhao’,22,‘M’);
INSERT INTO test_1 VALUES(11,‘zhao’,22,‘M’);
INSERT INTO test_1 VALUES(12,‘zhao’,22,‘M’);
UPDATE test_1 SET t_age = 30 WHERE t_id = 10;
DELETE test_1 WHERE t_id = 10;
–然後檢視效果
SELECT * FROM test_1;
SELECT * FROM test_1_log;
SELECT * FROM A1;
SELECT * FROM b1;
SELECT * FROM c1;
清空資料
truncate table test_1;
truncate table test_1_log;
truncate table a1;