0

I have a table with date of birth and I want to use a CreateFunction to calculate their age.

So I was thinking along the lines of extracting year from current date - Year for their date of birth (using YEAR() function as shown below)

The function below doesn't seem to work so any help would be appreciated!

DELIMITER $$
 
CREATE FUNCTION customer_age(DateOfBirth DATE)
RETURNS DATE
BEGIN
    DECLARE age DATE
    
    SET age = YEAR(curdate())- YEAR(DateOfBirth);
    
    RETURN (age);
    
    END $$
    
DELIMITER;

1 Answers1

0

You get an integer not a date,

See example

CREATE FUNCTION customer_age(DateOfBirth DATE)
RETURNS INT DETERMINISTIC
BEGIN
    DECLARE age INT;
    SET age = YEAR(curdate())- YEAR(DateOfBirth);
    
    RETURN age;
    
    END
SELECT customer_age('1970-01-01')
| customer_age('1970-01-01') |
| -------------------------: |
|                         51 |

db<>fiddle here

nbk
  • 45,398
  • 8
  • 30
  • 47