Sub topic 1
Recap: the PL/SQL block as the building unit
Prerequisites
You should know basic SQL (SELECT, INSERT, UPDATE, DELETE), anonymous PL/SQL blocks (DECLARE, BEGIN, EXCEPTION, END), Oracle data types such as NUMBER, VARCHAR2, and DATE, and have a schema where you hold the CREATE PROCEDURE privilege.
Recap: the PL/SQL block
A PL/SQL block has a declaration section, an execution section, and an optional exception section. A stored subprogram uses the same structure. Oracle saves it in the database under a name, so any code with permission can call it.
Procedures and functions
A procedure performs an action and does not return a value in an expression. A function returns one value and can appear inside SQL statements. Use a procedure for changes such as updates. Use a function to compute a value.
Creating and replacing a stored procedure
CREATE OR REPLACE creates the subprogram or replaces an existing version. %TYPE copies the data type of a column, so the parameter stays correct if the column type changes.
CREATE OR REPLACE PROCEDURE raise_salary (
p_employee_id IN employees.employee_id%TYPE,
p_percent IN NUMBER DEFAULT 10
) AS
BEGIN
UPDATE employees
SET salary = salary * (1 + p_percent / 100)
WHERE employee_id = p_employee_id;
IF SQL%ROWCOUNT = 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Employee not found: ' || p_employee_id);
END IF;
END raise_salary;
/The procedure checks SQL%ROWCOUNT after the update. If no row changed, it raises an error with a number between -20000 and -20999.
Creating a stored function and returning a value
A function declares its return type after the parameter list and returns a value with RETURN.
CREATE OR REPLACE FUNCTION get_full_name (
p_employee_id IN employees.employee_id%TYPE
) RETURN VARCHAR2 AS
v_name VARCHAR2(100);
BEGIN
SELECT first_name || ' ' || last_name
INTO v_name
FROM employees
WHERE employee_id = p_employee_id;
RETURN v_name;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
END get_full_name;
/Passing data in and out with IN, OUT, and IN OUT
Each parameter has a mode that sets its direction.
| Mode | Direction | Default |
|---|---|---|
| IN | Caller to subprogram (read only) | Yes |
| OUT | Subprogram to caller (write only) | No |
| IN OUT | Both directions | No |
CREATE OR REPLACE PROCEDURE get_salary_range (
p_job_id IN employees.job_id%TYPE,
p_min OUT NUMBER,
p_max OUT NUMBER
) AS
BEGIN
SELECT MIN(salary), MAX(salary)
INTO p_min, p_max
FROM employees
WHERE job_id = p_job_id;
END get_salary_range;
/> Note: Use / on its own line after each CREATE statement in SQL*Plus or SQL Developer to compile it. If compilation fails, query user_errors to see the line and message.
Exercise
What does getfullname return when no employee has the ID you pass?
Show answer
It returns NULL. The NODATAFOUND handler catches the missing row and returns NULL instead of raising an error.