diff --git a/Practical/Practical Exam/PL-SQL/P7 - Age_calc.md b/Practical/Practical Exam/PL-SQL/P7 - Age_calc.md new file mode 100644 index 0000000..62161a4 --- /dev/null +++ b/Practical/Practical Exam/PL-SQL/P7 - Age_calc.md @@ -0,0 +1,48 @@ +# P7 - Age_calc function + +## Creating function + +```sql +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 + +```sql +BEGIN + DBMS_OUTPUT.PUT_LINE(Age_calc(TO_DATE('2004-04-28', 'YYYY-MM-DD'))); +END; +/ + +``` + +---