I’m working on a PL/SQL script that finds the employee with the longest service time from a staff table. The program should calculate their years of service and display all their details using records and composite data types.
My code runs without errors but the service calculation part returns empty. I’m trying to use MONTHS_BETWEEN function to find the difference between current date and hire date. The logic seems right but something is wrong with how I’m handling the variables in my record structure.
The expected output should show something like:
Service Time: 9113.5 days or 303.8 months
Here’s my current code:
SET SERVEROUTPUT ON
DECLARE
TYPE staff_record IS RECORD
(
service_years NUMBER(4, 1),
start_date staff.start_date%TYPE,
staff_row staff%ROWTYPE
);
my_staff_rec staff_record;
BEGIN
SELECT * INTO my_staff_rec.staff_row
FROM
(
SELECT *
FROM staff
ORDER BY start_date
)
WHERE rownum = 1;
my_staff_rec.service_years :=
TRUNC(MONTHS_BETWEEN(SYSDATE, my_staff_rec.start_date), 1);
DBMS_OUTPUT.PUT_LINE('Senior employee details: '
|| my_staff_rec.staff_row.emp_id
|| ' ' || my_staff_rec.staff_row.fname
|| ' ' || my_staff_rec.staff_row.lname );
DBMS_OUTPUT.PUT_LINE('Started on: ' || my_staff_rec.staff_row.start_date);
DBMS_OUTPUT.PUT_LINE('Email: ' || my_staff_rec.staff_row.email_addr);
DBMS_OUTPUT.PUT_LINE('Contact: ' || my_staff_rec.staff_row.contact_num);
DBMS_OUTPUT.PUT_LINE('Service time: ' || my_staff_rec.service_years );
END;
/
The output shows all employee info correctly but the service time field is blank. What am I missing in my variable assignment or calculation?