PostgreSQL trigger on insert or update

I have two tables. I want to create a trigger in a table carthat will be inserted or deleted in the table fueldepending on a specific value.

Car

id - SERIAL
fuel - BOOLEAN

Fuel

car_id -  INTEGER

I do not include these lines, since the trigger description is not needed.

Basically, I want to create a trigger in a table carthat:

  • Works with insert or update.
  • Inserts Car.idinto a table fuelif Car.fuel is true.
  • If Car.fuel is false, the trigger should delete all rows in the table fuel, where Fuel.car_id = Car.id.

How should I do it?

EDIT: To clarify, I'm using Postgres

+5
source share
1 answer

, , Oracle. . , .

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;
+5

All Articles