Calculating age with currval in postgreSQL

110 Views Asked by At

I have created a database with a People table which contains all the information for people such as their first name, last name, gender,date of birth, and email. Each row in this table has a serial peopleID. I am trying to create a stored procedure and trigger to automatically calculate the age of a person that was just entered. I am trying to use currval to get the last inserted peopleID.

This is my stored procedure:

CREATE OR REPLACE FUNCTION PersonAge (peopleID INT)
RETURNS INTERVAL AS
$$
DECLARE
birthday date := (SELECT People.dateOfBirth
        FROM People
        );
BEGIN
RETURN age(birthday);
END;
$$
LANGUAGE plpgsql

This is my trigger:

CREATE TRIGGER CalculateAge
AFTER INSERT OR UPDATE ON People
FOR EACH ROW
EXECUTE PROCEDURE PersonAge( SELECT currval(‘people_id_seq’));

This is the error I am getting when I try to implement it with an insert statement:

ERROR:  syntax error at or near "currval"
LINE 5: EXECUTE PROCEDURE PersonAge( SELECT currval('people_id_seq')...
                                        ^
********** Error **********

ERROR: syntax error at or near "currval"
SQL state: 42601
Character: 116
1

There are 1 best solutions below

1
On

You pass arguments in not supported way, please read docs

Note that the function must be declared with no arguments even if it expects to receive some arguments specified in CREATE TRIGGER — such arguments are passed via TG_ARGV, as described below.

and

TG_ARGV[]

Data type array of text; the arguments from the CREATE TRIGGER statement. The index counts from 0. Invalid indexes (less than 0 or greater than or equal to tg_nargs) result in a null value.

(emphasis mine)