我想开发一个在插入或更新后更新触发器的触发器。
我遵循这个tutorial并创建了一个在插入后由触发器调用的函数。我和之前和之后都尝试过。
DROP TRIGGER IF EXISTS answer_update_question_timestamp ON public.publications;
CREATE OR REPLACE FUNCTION trigger_update_question_timestamp()
RETURNS TRIGGER AS $func$
BEGIN
UPDATE publications SET new.last_edit_date = now() WHERE publicationid = new.publicationid;
RETURN NULL;
END;
$func$ LANGUAGE plpgsql;
CREATE TRIGGER answer_update_question_timestamp AFTER INSERT OR UPDATE ON publications
FOR EACH ROW EXECUTE PROCEDURE trigger_update_question_timestamp();
CREATE TABLE publications
(
publicationid SERIAL PRIMARY KEY,
body VARCHAR(1000) NOT NULL ,
creation_date TIMESTAMP DEFAULT now() NOT NULL,
userid INTEGER NOT NULL,
last_edit_date TIMESTAMP,
CONSTRAINT body_length CHECK (CHAR_LENGTH(body) >= 10 AND CHAR_LENGTH(body) <= 1000),
CONSTRAINT "FK_publications_users"
FOREIGN KEY ("userid") REFERENCES users ("userid") ON DELETE SET NULL ON UPDATE CASCADE
);
我注意到NEW不适用于FOR EACH STATEMENT
等操作,但我没有发现FOR EACH ROW
有人知道我做错了吗?
亲切的问候
答案 0 :(得分:1)
如果你想在插入或删除时将last_edit_date设置为now(),只需将default设置为now():
CREATE TABLE publications
(
...
last_edit_date TIMESTAMP DEFAULT now(),
....
);
如果你仍想去那里,而不是更新自己并返回null,为NEW分配一个新值:
NEW.last_edit_date := now();
RETURN NEW;
当你将一个更新表的函数分配给该表上触发更新的触发器
时,会发生无限循环pozs的讨论。更新 - OP的工作示例:
t=# CREATE TABLE publications
(
publicationid SERIAL PRIMARY KEY,
body VARCHAR(1000) NOT NULL ,
creation_date TIMESTAMP DEFAULT now() NOT NULL,
userid INTEGER NOT NULL,
last_edit_date TIMESTAMP
);
CREATE TABLE
t=# CREATE OR REPLACE FUNCTION trigger_update_question_timestamp()
RETURNS TRIGGER AS $func$
BEGIN
new.last_edit_date := now();
RETURN NEW;
END;
$func$ LANGUAGE plpgsql;
CREATE FUNCTION
t=# CREATE TRIGGER answer_update_question_timestamp BEFORE INSERT OR UPDATE ON publications
FOR EACH ROW EXECUTE PROCEDURE trigger_update_question_timestamp();
CREATE TRIGGER
t=# insert into publications select 1,'2',now(),3,null;
INSERT 0 1
t=# select * from publications;
publicationid | body | creation_date | userid | last_edit_date
---------------+------+----------------------------+--------+----------------------------
1 | 2 | 2017-03-30 15:28:10.897846 | 3 | 2017-03-30 15:28:10.897846
(1 row)