简体   繁体   中英

PostgreSQL: Insert a row in a table from multiple tables in AFTER INSERT TRIGGER

I have four tables

CREATE TABLE ExhibitionsCollection (
    EXC_ItemAlphaKey CHAR (4),
    EXC_ItemNumKey SMALLINT,
    EXC_ExhName  CHAR (15),
    PRIMARY KEY(EXC_ItemAlphaKey, EXC_ItemNumKey)
   );

 CREATE TABLE ExhibitionsLocation (
    EXL_ExhName CHAR (15),
    EXL_ExhLocation CHAR (20)
   );

CREATE TABLE Exhibitions (
    EX_ExhName CHAR (15),
    EX_ExhStartdate DATE,
    EX_ExhEnddate DATE,
    EX_ExhDescription TEXT
    );

 CREATE TABLE ItemsLocation (
     ITL_ItemAlphaKey CHAR (4),
     ITL_ItemNumKey SMALLINT,
     ITL_ItemLocation CHAR(15),
     ITL_Startdate DATE,
     ITL_Endate DATE
  );

I wanted to create an AFTER INSERT TRIGGER ON ExhibitionsCollection, something like this

CREATE TRIGGER trigger_ItemInsertedIntoExhibition
  AFTER INSERT  
  ON ExhibitionsCollection
  EXECUTE PROCEDURE somefuntion();

 CREATE OR REPLACE FUNCTION somefuntion() RETURNS TRIGGER AS
 $BODY$
   BEGIN


    INSERT INTO ItemsLocation (ITL_ItemAlphaKey, ITL_ItemNumKey, ITL_ItemLocation, ITL_Startdate, ITL_Enddate)

    /*I need to insert the values of those attributes with each new insertion in to ExhibitionsCollection*/

   END;
 $BODY$
  LANGUAGE plpgsql;

This (untested) statement assumes that the SELECT statement returns exactly one row, ie that exc_exhname and exc_exhname are foreign keys linking to the respective tables.

INSERT INTO itemslocation
   (itl_itemalphakey, itl_itemnumkey, itl_itemlocation, itl_startdate, itl_enddate)
   (SELECT
       NEW.exc_itemalphakey,
       NEW.exc_itemnumkey,
       exl.exl_exhlocation,
       ex.itl_startdate,
       ex.itl_enddate
    FROM exhibitionslocation exl, exhibitions ex
    WHERE exl.exl_exhname = NEW.exc_exhname
       AND ex.ex_exhname = NEW.exc_exhname
   );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM