Optional filtering in a SQL query
715809Nov 12 2009 — edited Nov 12 2009Say I want to write a stored procedure on the EMP table, which would return NAME, DEPT, SALARY, IS_ACTIVE of an employee (record in EMP) for a given DEPT_ID. Suppose I'd like to return it as a REF CURSOR and also that the caller might want to skip (or not) records with IS_ACTIVE='N'
The way I've seen it implemented (and don't like it) is:
FUNCTION get_employees_list( p_dept_id IN EMP.DEPT_ID%TYPE, return_only_active IN VARCHAR2 DEFAULT 'Y' )
retval a_ref_cursor;
IF (return_only_active= 'Y' ) THEN
-- return only active employees
OPEN retval FOR
SELECT NAME, SALARY
FROM EMP
WHERE DEPT_ID=p_dept_id AND
IS_ACTIVE = 'Y';
ELSE
-- return all employees, active or not
OPEN retval FOR
SELECT NAME, SALARY
FROM EMP
WHERE DEPT_ID=p_dept_id;
END IF;
RETURN retval;
END get_employees_list;
I found this a bit silly. Is there a better way?
Thank you.