我想创建一个触发器,这样每当我进行更改(更新或删除)时,它都应该将旧数据复制到一个新表(使用相同的模板)。
我试过这段代码:
create table restrictions(ID int,name text);
insert into restrictions values(122,'suresh');
select * from restrictions;
create table restrictions_deleted(ID int,name text);// this is my duplicate table for keeping information of all updations.
CREATE OR REPLACE FUNCTION moveDeleted() RETURNS trigger AS $$
BEGIN
INSERT INTO restrictions_deleted VALUES(OLD.ID, OLD.name);
RETURN OLD;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE TRIGGER moveDeleted
BEFORE DELETE ON restrictions
FOR EACH ROW
EXECUTE PROCEDURE moveDeleted();
delete from restrictions where ID=122;
select * from restrictions_deleted;
此代码能够将所有已删除的数据记录到重复的表中。但我也想对更新做同样的事情。
任何建议,任何想法?
答案 0 :(得分:0)
首先 - 在触发功能中,您需要RETURN NEW;
而不是RETURN OLD;
。
其次 - 将触发器更改为BEFORE DELETE OR UPDATE
。
最后 - 最好让AFTER DELETE OR UPDATE
用于记录触发器。这样,当更改被回滚时,它不会做无用的工作。
BTW here
是记录/审核触发器的一个很好的例子。
更新:
该功能如下:
CREATE OR REPLACE FUNCTION moveDeleted() RETURNS trigger AS $$
BEGIN
IF (TG_OP = 'UPDATE') THEN
INSERT INTO restrictions_deleted VALUES(OLD.ID, OLD.name);
RETURN NEW;
ELSIF (TG_OP = 'DELETE') THEN
INSERT INTO restrictions_deleted VALUES(OLD.ID, OLD.name);
RETURN OLD;
END IF;
END;
$$ LANGUAGE plpgsql;