Insert trigger to Update another table using PostgreSQL

后端 未结 2 858
一向
一向 2020-12-14 17:34

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?

相关标签:
2条回答
  • 2020-12-14 17:50

    You want the documenation for PL/PgSQL triggers, which discusses just this case among others. The general documentation on triggers may also be useful.

    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.

    0 讨论(0)
  • 2020-12-14 18:09

    Here we have two tables named table1 and table2. Using a trigger I'll update table2 on insertion into 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();
    
    0 讨论(0)
提交回复
热议问题