I am trying to implement a procedure within mysql that returns the age based on a calculation.
The date of birth (DATE) is passed in and then the calculation is done. Should be relatively straight forward but I cannot seem to get it to work. I am not sure if this is an appropriate situation for a “select statement” and
I apologize if this is extremely simple but this is my first run at procedures.
If somebody could please tell me what I am doing wrong, it would be much appreciated.
Thanks!
P.S. I have a table called “PERSON” that contains the field “age” (int) which is currently empty until the stored procedure is called.
DELIMITER $$
CREATE PROCEDURE determineAge(IN birthDate DATE)
BEGIN
DECLARE today TIMESTAMP;
SELECT DATEDIFF(today,birthdate)/365 AS ageInYears
FROM PERSON;
END $$
DELIMITER ;
call determineAge('June 25, 1981');
This works. No need to declare “today” – just use a
NOW()function in your query.Also, no need to select
FROManything… you’re just querying a single value.Your date was formatted wrong (MySQL requires
'YYYY-MM-DD', and you want to floor the difference to get a whole number of years.Finally, you could theoretically return the year value as an
OUTparam if you wanted to, though a query result is just fine.There you go!