PostgreSQL 在插入或更新时触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14772192/
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-10-21 00:47:20  来源:igfitidea点击:

PostgreSQL Trigger on Insert or Update

sqlpostgresqltriggersconstraints

提问by Ozzy

I have two tables. I want to create a trigger on the cartable which will insert or delete on the fueltable depending on a certain value.

我有两张桌子。我想在car表上创建一个触发器,它将fuel根据某个值在表上插入或删除。

Car

id - SERIAL
fuel - BOOLEAN

Fuel

燃料

car_id -  INTEGER

I am not including any row data as the description of the trigger does not need it.

我不包括任何行数据,因为触发器的描述不需要它。

Basically, I want to create a trigger on the Cartable that:

基本上,我想在Car表上创建一个触发器:

  • Runs on an insert or update.
  • Inserts Car.idinto Fueltable if Car.fuel is true.
  • If Car.fuel is false, the trigger should delete all rows in the Fueltable where Fuel.car_id = Car.id.
  • 在插入或更新时运行。
  • 如果 ,则插入Car.idFuel表中Car.fuel is true
  • 如果Car.fuel is false,触发器应该删除Fuel表中的所有行where Fuel.car_id = Car.id

How would I do this?

我该怎么做?

EDIT: To clarify I am using Postgres

编辑:为了澄清我正在使用 Postgres

采纳答案by Orangecrush

Since you haven't mentioned the RDBMS, I assume it is Oracle. Below is the trigger. If you are using another RDBMS, tweak the code to fit the syntax.

由于您还没有提到 RDBMS,我假设它是 Oracle。下面是触发器。如果您使用另一个 RDBMS,请调整代码以适应语法。

CREATE OR REPLACE TRIGGER TRG_CAR
   AFTER INSERT OR UPDATE ON CAR
   FOR EACH ROW

   BEGIN

     IF :new.FUEL THEN
       INSERT INTO FUEL (CAR_ID) VALUES (:new.ID);
     ELSE
       DELETE FROM FUEL WHERE CAR_ID = :new.ID;
     END IF;
   END;