PostgreSQL Trigger error
You need to use FOR EACH ROW
CREATE TRIGGER triggerPodan AFTER INSERT OR DELETEON "Podania" FOR EACH ROWEXECUTE PROCEDURE aktualizujIloscPodan();
For the delete
trigger only OLD
record is defined and NEW
is undefined. So, in the code, check if the trigger is running as DELETE
or INSERT
(variable TG_OP
) and access the appropriate record.
Besides, you can go without counting here at all, like this:
CREATE OR REPLACE FUNCTION aktualizujIloscPodan() RETURNS TRIGGER AS$BODY$ DECLARE n integer;BEGIN IF TG_OP = 'INSERT' then UPDATE "Studenci" SET "ilosc_podan" = "ilosc_podan" + 1 WHERE "ID"=NEW."studentID"; ELSIF TG_OP = 'DELETE' then UPDATE "Studenci" SET "ilosc_podan" = "ilosc_podan" - 1 WHERE "ID"=OLD."studentID"; END IF;END;$BODY$ LANGUAGE plpgsql;DROP TRIGGER IF EXISTS triggenPodan ON "Podania";CREATE TRIGGER triggenPodan AFTER INSERT OR DELETEON "Podania" FOR EACH ROWEXECUTE PROCEDURE aktualizujIloscPodan();