更新时间:2021-11-28 01:05:15
Postgres中的触发器不直接提供触发器代码,而是调用 trigger函数,该函数可以从任意数量的触发器中调用,尽管通常它们是针对一个特定表上的一个特定事件而定制的.
Triggers in Postgres don't provide trigger code directly, but call a trigger function, which can be called from any number of triggers, though often they are customized for one particular event on one particular table.
触发功能:
CREATE OR REPLACE FUNCTION trg_some_tbl_foo()
RETURNS trigger AS
$func$
BEGIN
INSERT INTO some_tbl(key, name, describe) -- or some_other_tbl?
VALUES (OLD.key, OLD.name, OLD.describe);
RETURN OLD;
END
$func$ LANGUAGE plpgsql
CREATE TRIGGER foo -- not: "CREATE OR REPLACE" !
AFTER UPDATE OR DELETE ON some_tbl
FOR EACH ROW EXECUTE PROCEDURE trg_some_tbl_foo()
为它添加一个 AFTER
触发器以简化操作. BEFORE
触发器必须进行 RETURN NEW
才能使更新生效,但是 NEW
在 DELETE
触发器中不可见.因此,您需要 IF TG_OP = ...
等.
Make it an AFTER
trigger to simplify. A BEFORE
trigger would have to RETURN NEW
to make updates work, but NEW
is not visible in a DELETE
trigger. So you'd need IF TG_OP = ...
etc.
始终为持久化的 INSERT
语句提供目标列表.在Oracle触发器中也是如此.
Always provide a target list for persisted INSERT
statements. This is just as bad in an Oracle trigger.
您可能有一个带有 serial
列的表.只是不要在插入内容中提及它,序列中的下一个ID会自动插入.
You probably have a table with a serial
column. Just don't mention it in the insert, the next id from the sequence is inserted automatically.
SO上有许多代码示例.
There are numerous code examples here on SO.