If you have the tables:
CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR2(20)
);
CREATE TABLE employees (
first_name VARCHAR2(20),
last_name VARCHAR2(20),
hire_date DATE,
department_id INT REFERENCES departments ( department_id )
);
INSERT ALL
INTO departments VALUES ( 1, 'Dept. A' )
INTO employees VALUES ( 'Alice', 'Adams', DATE '2020-01-01', 1 )
INTO employees VALUES ( 'Betty', 'Baron', DATE '2020-02-01', 1 )
INTO employees VALUES ( 'Cerys', 'Carol', DATE '2020-03-01', 1 )
SELECT * FROM DUAL;
Then you can create the package:
CREATE PACKAGE employees_pkg
IS
TYPE emp_type IS RECORD(
first_name EMPLOYEES.FIRST_NAME%TYPE,
last_name EMPLOYEES.LAST_NAME%TYPE
);
FUNCTION get_employee(
P_DEPT_NAME IN DEPARTMENTS.DEPARTMENT_NAME%type,
P_YEAR IN NUMBER
) RETURN emp_type;
END;
/
(Note: the package specification only contains the signatures for the function.)
And its body:
CREATE PACKAGE BODY employees_pkg
IS
FUNCTION get_employee(
P_DEPT_NAME IN DEPARTMENTS.DEPARTMENT_NAME%type,
P_YEAR IN NUMBER
) RETURN emp_type
IS
v_year DATE := TRUNC( TO_DATE( p_year, 'YYYY' ), 'YYYY' );
v_emp emp_type;
BEGIN
SELECT e.first_name, e.last_name
INTO v_emp.first_name, v_emp.last_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id
WHERE d.department_name = p_dept_name
AND e.hire_date >= v_year
AND e.hire_date < ADD_MONTHS( v_year, 12 )
ORDER BY e.hire_date
FETCH FIRST ROW ONLY;
RETURN v_emp;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- your code to handle the exception
NULL;
END;
END;
/
Note:
SELECT ... INTO ... only accepts a single row so you can limit the query to return at most one row using FETCH FIRST ROW ONLY and also handle the NO_DATA_FOUND exception in case there are no employees.
- You also don't want to mix cursors and
SELECT ... INTO ..., just use the latter.
Then you can call it:
DECLARE
v_emp employees_pkg.emp_type;
BEGIN
v_emp := employees_pkg.get_employee(p_dept_name => 'Dept. A', p_year => 2020 );
DBMS_OUTPUT.PUT_LINE( v_emp.first_name || ' ' || v_emp.last_name );
END;
/
Which outputs:
Alice Adams
db<>fiddle here