14th Example - Calculate Your Age on PL/SQL


We have learned the basics of PL/SQL block from the start structured, selection, looping and exception. Let us now try to make a block of PL/SQL to solve real problems. The following will be shown examples of PL/SQL to calculate a person's age. Person's age can be determined from the difference between the current date with the date of birth.

DECLARE
        tlahir DATE;
        umur NUMBER;
BEGIN
        --ENter your birth data with DD-MM-YYYY (ex: 17-02-1990)
        tlahir := TO_DATE('&indate', 'DD-MM-YYYY');
        umur := FLOOR((SYSDATE - tlahir)/365);
        DBMS_OUTPUT.PUT_LINE ('Your age is '||umur||' years old');
END;
/

Above PL/SQL block have 2 variables, tlahir with DATE data type and age with NUMBER data type. Tlahir variable will receive input from a keyboard entry date of birth in the format DD-MM-YYYY. Umur variable will make the process of calculating the difference between SYSDATE (current date) with tlahir (date of birth) were divided by 365 (days in a year). To generate integers by rounding down is used FLOOR function. If the input is "17-02-1990" then the output is "Your age is 23 years old".

No comments

Powered by Blogger.