插入触发器以使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 23:42:49  来源:igfitidea点击:

Insert trigger to Update another table using PostgreSQL

postgresqltriggers

提问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 table1and table2. Using a trigger I'll update table2on 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 BEFOREor AFTERtrigger for this. I'd probably use an AFTERtrigger so that my trigger saw the final version of the row being inserted, though. You want FOR EACH ROW, of course.

为此,您可以使用 aBEFOREAFTER触发器。不过,我可能会使用AFTER触发器,以便我的触发器看到正在插入的行的最终版本。你想要FOR EACH ROW,当然。