user3321757
user3321757

Reputation: 41

PL/SQL exception-handling

I have PL/SQL anonymous block to work with finding an employees based on their department_id. I wrote a procedure for that.

Code

CREATE OR REPLACE PROCEDURE find_employees (
    p_dept_no         IN     NUMBER,
    p_error_message      OUT VARCHAR2)
AS
    v_dept_no   NUMBER;
    dept_chk    EXCEPTION;

    CURSOR find_emp
    IS
        SELECT employee_id,
               first_name,
               last_name,
               salary,
               hire_date
          FROM employees
         WHERE department_id = p_dept_no;
BEGIN
    -- Check if the department_id in departments table
    IF Condition
    THEN                                --Need to check the condition here
        RAISE dept_chk;
    END IF;

    FOR i IN find_emp
    LOOP
        DBMS_OUTPUT.put_line (i.employee_id);
        DBMS_OUTPUT.put_line (i.first_name);
        DBMS_OUTPUT.put_line (i.last_name);
        DBMS_OUTPUT.put_line (i.salary);
        DBMS_OUTPUT.put_line (i.hire_date);
    END LOOP;
EXCEPTION
    WHEN dept_chk
    THEN
        p_error_message := 'Please enter valid department number';
END find_employees;

Note:

On that procedure there is one input parameter p_dept_no as INPUT and p_error_message is the output parameter.

I need to check the if the department_id is in in the departments table then automatically the records will show other wise it's showing an exception so there i need to check the condition how it's possible let me know Thanks in advance.

Upvotes: 0

Views: 453

Answers (1)

Aleksej
Aleksej

Reputation: 22949

Given that you already scan the table, you can simply set a variable in within the loop and check its value outside. For example:

CREATE OR REPLACE PROCEDURE find_employees(p_dept_no IN 
NUMBER,p_error_message OUT VARCHAR2)
AS 
    v_dept_no NUMBER;
    dept_chk EXCEPTION;
    vEmployeeFound boolean := false;  -- a boolean variable
CURSOR find_emp 
   IS 
SELECT 
    employee_id,  first_name,  last_name,  salary,  hire_date
FROM    
    employees
WHERE
    department_id = p_dept_no;
BEGIN    

FOR i in find_emp
LOOP
    dbms_output.put_line(i.employee_id);
    dbms_output.put_line(i.first_name);
    dbms_output.put_line(i.last_name);
    dbms_output.put_line(i.salary);
    dbms_output.put_line(i.hire_date);
    vEmployeeFound := true;                   -- set the variable
END LOOP;       

-- Check if the department_id in departments table
IF  NOT vEmployeeFound  THEN -- check the variable value
    RAISE dept_chk;
END IF;

EXCEPTION
    WHEN dept_chk THEN
    p_error_message:='Please enter valid department number';
END find_employees;

Upvotes: 1

Related Questions