我想写一个触发器来跟踪一张桌子。
我有一张表1和表2。当我将数据插入表1时,触发器成功地将相同的数据插入到表2中,但是当我更新table1时,table2仍然具有相同的相同数据
表格DDL:
TAB1
身份证号码(6);
info varhcar2(20);
TAB2
身份证号码(6);
info varchar2(20);
id_new number(6);
info_new varchar2(20);
触发器:
CREATE OR REPLACE TRIGGER tab2_logs
after INSERT or update or delete
ON tab1
FOR EACH ROW
DECLARE
BEGIN
IF INSERTING THEN
insert into tab2_logs (
id, info)
values (:new.id ,:new.info);
else if updating then
update tab2_logs set
id = :old.id,
info = :old.info,
id_new = :new.id,
info_new = :new.id
where id = :new.id;
end if;
end if;
END;
我确实在我的查询中提交并且触发器编译成了succedfuly
答案 0 :(得分:1)
我认为你想要做的是:
将tab2_logs更改为列:
id, info, id_old, info_old
然后使用以下触发器:
CREATE OR REPLACE TRIGGER tab2_logs AFTER
INSERT OR
UPDATE OR
DELETE
ON tab1 FOR EACH ROW DECLARE BEGIN IF INSERTING THEN
INSERT
INTO
tab2_logs
(
id,
info
)
VALUES
(
:new.id ,
:new.info
);
elsif updating THEN
UPDATE
tab2_logs
SET
id = :new.id,
info = :new.info,
id_old = :old.id,
info_old = :old.info
WHERE
id = :old.id;
END IF;
END;
<强> SQLFiddle 强>
答案 1 :(得分:0)
添加dbms_output.put_line()以查找执行路径
- 旧答案 - 根据上次评论没有任何意义 看起来你的更新没找到记录int tab2_log也许你需要改变
where id = :new.id;
到
where id = :old.id;
还有更好的记录方式(在我看来)
create or replace trigger tab2_logs
after insert or update or delete on tab1
for each row
begin
if INSERTING or updating then
-- also need add information about time and user who change row
insert into tab2_logs (id, info) values (:new.id, :new.info);
end if;
end;