0
DELIMITER $$
CREATE FUNCTION current_age (birthdate date)
RETURNS date
BEGIN
        DECLARE age_return date;
        DECLARE rightnow date;
        SET rightnow = date(now());
        SET age_return = timestampdiff(year, rightnow, date(birthdate));
        RETURN age_return;
END  $$
DELIMITER ;

select current_age(date('2017-06-30'));

I am trying to create a function which years the difference in years. I cant get it to work and I dont understand why, because the following works fine outside the function.

SET @birthdate = '2001-01-01';
SET @rightnow = date(now());
SELECT timestampdiff(year, @rightnow, date(@birthdate))
1
  • 2
    cant get it to work means? Commented Jan 31, 2018 at 20:12

1 Answer 1

1

If we want to return a number of years, then the return type would be a numeric type like INT or DECIMAL. We wouldn't return a DATE datatype.

DELIMITER $$

CREATE FUNCTION current_age(birthdate DATE)
RETURNS INT
BEGIN
  RETURN TIMESTAMPDIFF(YEAR,birthdate,DATE(NOW()));
END$$

DELIMITER ;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.