插入触发器以使用 PostgreSQL 更新另一个表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12343984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert trigger to Update another table using PostgreSQL
提问by user1658873
I have a table named awards. How can I mount a Trigger in PostgreSQL where each insert in the table awards updates a different table?
我有一张名为 Awards 的表。如何在 PostgreSQL 中安装触发器,其中表中的每个插入都会更新不同的表?
回答by Sachin Gupta
Here we have two tables named table1
and table2
. Using a trigger I'll update table2
on insertion into table1
.
这里我们有两个名为table1
和 的表table2
。使用触发器,我将table2
在插入table1
.
Create the tables
创建表
CREATE TABLE table1
(
id integer NOT NULL,
name character varying,
CONSTRAINT table1_pkey PRIMARY KEY (id)
)
CREATE TABLE table2
(
id integer NOT NULL,
name character varying
)
The Trigger Function
触发功能
CREATE OR REPLACE FUNCTION function_copy() RETURNS TRIGGER AS
$BODY$
BEGIN
INSERT INTO
table2(id,name)
VALUES(new.id,new.name);
RETURN new;
END;
$BODY$
language plpgsql;
The Trigger
触发
CREATE TRIGGER trig_copy
AFTER INSERT ON table1
FOR EACH ROW
EXECUTE PROCEDURE function_copy();
回答by Craig Ringer
You want the documenation for PL/PgSQL triggers, which discusses just this case among others. The general documentation on triggersmay also be useful.
您需要PL/PgSQL triggers的文档,其中仅讨论了这种情况。有关触发器的一般文档也可能有用。
You can use either a BEFORE
or AFTER
trigger for this. I'd probably use an AFTER
trigger so that my trigger saw the final version of the row being inserted, though. You want FOR EACH ROW
, of course.
为此,您可以使用 aBEFORE
或AFTER
触发器。不过,我可能会使用AFTER
触发器,以便我的触发器看到正在插入的行的最终版本。你想要FOR EACH ROW
,当然。