Example of a PL/SQL procedure that calculates the total salary of
employees in a specific department:
CREATE OR REPLACE PROCEDURE calculate_department_salary(
department_id IN NUMBER,
total_salary OUT NUMBER
)
IS
BEGIN
SELECT SUM(salary)
INTO total_salary
FROM employees
WHERE department_id = department_id;
-- If no employees are found in the department, set total_salary
to 0
IF total_salary IS NULL THEN
total_salary := 0;
END IF;
END;
/
EXPLANATION:
:
CREATE OR REPLACE PROCEDURE
calculate_department_salary: This line defines the
start of the procedure named
calculate_department_salary. If the procedure
already exists, OR REPLACE ensures it's replaced
with the new definition.
(department_id IN NUMBER, total_salary OUT
NUMBER): These are the parameters passed to the
procedure. department_id is an input parameter
(denoted by IN) representing the department ID for
which we want to calculate the total salary.
total_salary is an output parameter (denoted by
OUT) where the calculated total salary will be stored.
IS: Marks the beginning of the executable part of the
procedure.
BEGIN and END;: These keywords delineate the
start and end of the procedure's body, where the
actual work is done.
SELECT SUM(salary) INTO total_salary FROM
employees WHERE department_id =
department_id;: This SQL statement calculates the
total salary of employees in the specified department
and assigns it to the total_salary parameter using
the INTO clause.
IF total_salary IS NULL THEN total_salary := 0;
END IF;: Checks if no employees are found in the
specified department. If total_salary is NULL
(meaning no records were returned by the query), it
sets total_salary to 0 to handle this case gracefully.
This procedure can be called like this:
DECLARE
dept_salary NUMBER;
BEGIN
calculate_department_salary(10, dept_salary);
DBMS_OUTPUT.PUT_LINE('Total salary for
department 10: ' || dept_salary);
END;
/