PostgreSQL:在AFTER INSERT TRIGGER

时间:2016-10-16 07:21:29

标签: sql postgresql

我有四张桌子

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
  );

我想在ExhibitionsCollection上创建一个AFTER INSERT TRIGGER,就像这样

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;

1 个答案:

答案 0 :(得分:0)

这个(未经测试的)语句假定SELECT语句只返回一行,即exc_exhnameexc_exhname是链接到各个表的外键。

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
   );