Postgresql – I can’t figure out how to call a function with a trigger, keeps saying function doesn’t exist

functionspostgresqltrigger

CREATE OR REPLACE FUNCTION calculate(nr char) RETURNS char AS $$
    BEGIN

      RETURN (SELECT COUNT(*) FROM patient_notitie WHERE pn_patient_nr = nr);

    END;
$$ LANGUAGE plpgsql;

This worked:

SELECT * FROM calculate('100001');

This is where it went wrong, when we try to create the trigger to call the function:

CREATE TRIGGER trigger_calculate AFTER INSERT ON patient_notitie
EXECUTE PROCEDURE calculate(pn_patient_nr);

It says the function doesn't exist:

ERROR: function calculate() does not exist SQL state: 42883

Best Answer

Before creating trigger, you need to create a trigger function, which has to be (quoting the manual):

A user-supplied function that is declared as taking no arguments and returning type trigger

Like:

CREATE OR REPLACE FUNCTION calculate_t_f()
  RETURNS trigger AS
$$
BEGIN
...
-- do something
-- maybe with with calculate(char)...
...
END
$$ LANGUAGE plpgsql;

Then you can create your trigger with that trigger function (not your original function):

CREATE TRIGGER trigger_calculate
AFTER INSERT ON patient_notitie
EXECUTE PROCEDURE calculate_t_f();