0

我想创建一个触发器,以便每当我进行更改(更新或删除)时,它都应该将旧数据复制到新表中(使用相同的模板)。

我试过这段代码:

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;

此代码能够将所有已删除的数据记录到重复表中。但我也想对更新做同样的事情。

有什么建议,有什么想法吗?

4

1 回答 1

1

首先-在触发功能中,您需要RETURN NEW;代替RETURN OLD;.

第二 - 将触发器更改为BEFORE DELETE OR UPDATE

最后 - 最好有AFTER DELETE OR UPDATE一个日志记录触发器。这样,当更改回滚时,它就不会做无用的工作。

BTWhere是记录/审计触发器的一个很好的例子。

更新:

该函数将如下所示:

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;
于 2013-03-12T09:58:43.367 回答