Question

I have a problem with trigger. I have simple table stats. In this table I have for example: id, energy, is_alive. I need create a trigger ON UPDATE something like this:

CREATE TRIGGER AFTER UPDATE
IF energy <= 0 THEN 
  UPDATE stats SET is_alive = false

and when I execute:

UPDATE stats SET energy = -3 WHERE id = 7

I would like:

  1. update value on - 3
  2. execute trigger and check is new value is <= 0
  3. if yes update is_alive = false on this record id = 7

Is this possible? Or does the trigger have to check all table and change all rows when energy will be <= 0?

Was it helpful?

Solution

A trigger function like this:

CREATE FUNCTION trg_stats_insup_bef()
  RETURNS trigger AS
$func$
BEGIN
IF NEW.energy <= 0 THEN
   NEW.is_alive := FALSE;
END IF;
RETURN NEW;
END
$func$ LANGUAGE plpgsql;

And a trigger (BEFORE, not AFTER):

CREATE TRIGGER insup_bef
BEFORE INSERT OR UPDATE OF energy ON stats  -- covers INSERT, too
FOR EACH ROW
EXECUTE PROCEDURE trg_stats_insup_bef()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top