0

我只想维护当前 1 个月的记录日志详细信息。需要删除过去的记录日志详细信息。我尝试了此代码但无法正常工作,

create sequence userseq1;

CREATE TABLE users
( id integer NOT NULL DEFAULT nextval('userseq1'::regclass) 
);

INSERT INTO users VALUES(126);

CREATE TABLE History
( userid integer
, createdate timestamp
);

CREATE OR REPLACE FUNCTION recordcreatetime() RETURNS trigger language plpgsql
AS $$
DECLARE
BEGIN
    INSERT INTO History values(new.id,NOW() );
    RETURN NEW;
END;
$$;

CREATE TRIGGER user_hist
BEFORE INSERT ON users
FOR EACH ROW
EXECUTE procedure recordcreatetime();

但是,它正在插入一个一个顺序添加的值。我想删除前 1 个月的记录日志详细信息。我尝试了下面的代码,但它不起作用

CREATE OR REPLACE FUNCTION trf_keep_row_number_steady()
RETURNS TRIGGER AS 
$body$
DECLARE
BEGIN
        IF (SELECT count(createdate) FROM history) > rownum_limit
    THEN 
        DELETE FROM history
        WHERE createdate = (SELECT min(createdate) FROM history);        
    END IF;
END;
$body$
LANGUAGE plpgsql;

CREATE TRIGGER tr_keep_row_number_steady 
AFTER INSERT ON history
FOR EACH ROW EXECUTE PROCEDURE trf_keep_row_number_steady();
4

1 回答 1

1

我可以在你的第二个代码块中看到,你在history桌子上有一个触发器,你正试图DELETE FROM history在同一个触发器中。

不允许通过同一张表上的触发器在表上插入/更新/删除。请考虑其他一些替代方法,例如,在主语句之前或之后运行单独的DELETE语句来清除所需的行INSERT

于 2013-03-26T07:49:27.817 回答