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
PostgreSQL Trigger on Insert or Update
提问by Ozzy
I have two tables. I want to create a trigger on the car
table which will insert or delete on the fuel
table 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 Car
table that:
基本上,我想在Car
表上创建一个触发器:
- Runs on an insert or update.
- Inserts
Car.id
intoFuel
table ifCar.fuel is true
. - If
Car.fuel is false
, the trigger should delete all rows in theFuel
table whereFuel.car_id = Car.id
.
- 在插入或更新时运行。
- 如果 ,则插入
Car.id
到Fuel
表中Car.fuel is true
。 - 如果
Car.fuel is false
,触发器应该删除Fuel
表中的所有行whereFuel.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;