Home > Back-end >  How to create a function that determines the age classification of an employee
How to create a function that determines the age classification of an employee

Time:03-06

I'm doing an assignment for a class where I should determine if the person's age is between one of the following categories:

AGE            CLASSIFICATION
0-14           Children
15-24          Early working age
25-54          Prime working age 
55-64          Mature working age 
65 and above   Elderly 

This is what my script currently looks like:

DELIMITER //
CREATE FUNCTION `Employee_age_classification`(`Employees_Last_Name` VARCHAR(50)) RETURNS varchar(50) CHARSET utf8mb4 
    DETERMINISTIC
BEGIN
DECLARE CLASS VARCHAR(50);
DECLARE AGE INT;
DECLARE LASTN VARCHAR(50);
SELECT TIMESTAMPDIFF(YEAR,Bdate,CURDATE())
INTO AGE
FROM EMPLOYEE
WHERE Lname = Employees_Last_Name;
IF AGE>=0 AND AGE<=14 THEN SET CLASS = 'Children';
ELSEIF AGE>=15 AND AGE<=24 THEN SET CLASS = 'Early Working Age';
ELSEIF AGE>=25 AND AGE<=54 THEN SET CLASS = 'Prime Working Age';
ELSEIF AGE>=55 AND AGE<=64 THEN SET CLASS = 'Mature Working Age';
ELSEIF AGE>=65 THEN SET CLASS = 'Elderly';
END IF;
RETURN CLASS;
DELIMITER;

It shows an error when I try to run it.

Error Code: 1064. You have an error in your SQL syntax. 

How can I fix this?

CodePudding user response:

You are missing an END statement before the last DELIMITER -

DELIMITER //
CREATE FUNCTION `Employee_age_classification`(`Employees_Last_Name` VARCHAR(50))
RETURNS varchar(50) CHARSET utf8mb4 
DETERMINISTIC
BEGIN
     DECLARE CLASS VARCHAR(50);
     DECLARE AGE INT;
     DECLARE LASTN VARCHAR(50);
     SELECT TIMESTAMPDIFF(YEAR,Bdate,CURDATE())
       INTO AGE
       FROM EMPLOYEE
      WHERE Lname = Employees_Last_Name;
     IF AGE>=0 AND AGE<=14 THEN 
        SET CLASS = 'Children';
     ELSEIF AGE>=15 AND AGE<=24 THEN 
        SET CLASS = 'Early Working Age';
     ELSEIF AGE>=25 AND AGE<=54 THEN 
        SET CLASS = 'Prime Working Age';
     ELSEIF AGE>=55 AND AGE<=64 THEN 
        SET CLASS = 'Mature Working Age';
     ELSEIF AGE>=65 THEN 
        SET CLASS = 'Elderly';
     END IF;
     RETURN CLASS;
END//
DELIMITER;
  • Related