DatabaseManagementSystems/Practical/Practical Exam/PL-SQL/P7 - Age_calc.md

889 B

P7 - Age_calc function

Creating function

CREATE OR REPLACE FUNCTION Age_calc (p_dob IN DATE)
RETURN VARCHAR IS
-- declare
  ageOP VARCHAR2(255);
  years NUMBER;
  months NUMBER;
  days NUMBER;

BEGIN

  years := EXTRACT(YEAR FROM SYSDATE) - EXTRACT(YEAR FROM p_dob);
  months := EXTRACT(MONTH FROM SYSDATE) - EXTRACT(MONTH FROM p_dob);
  days := EXTRACT(DAY FROM SYSDATE) - EXTRACT(DAY FROM p_dob);

  IF (days < 1) THEN
    months := months - 1;
    days := days + EXTRACT(DAY FROM LAST_DAY(ADD_MONTHS(SYSDATE, -1)));
  END IF;

  IF (months < 1) THEN
    years := years - 1;
    months := months + 12;
  END IF;

  ageOP := 'Given person is ' || years || ' years ' || months || ' months ' || days || ' days old.';

RETURN ageOP;
END Age_calc;
/

Calling function

BEGIN
  DBMS_OUTPUT.PUT_LINE(Age_calc(TO_DATE('2004-04-28', 'YYYY-MM-DD')));
END;
/