PL/SQL Stored Procedures π€ΒΆ
Prerequisites: PL/SQL Basics, Exception Handling
Mentor's Note: An Anonymous block is a one-time thing. A Stored Procedure is a program that is Saved in the database. Anyone with permission can call it, from any app, any number of times. It's the ultimate tool for code reuse! π‘
π The Scenario: The Coffee Machine βΒΆ
- The Procedure: You write a program called
brew_coffee. - The Input (IN): You tell it how many sugars. π¬
- The Output (OUT): It gives you a cup of coffee. β
- The Result: You don't have to know how the machine works internally; you just "Call" the procedure.
π» 1. Creating a ProcedureΒΆ
CREATE OR REPLACE PROCEDURE welcome_user(p_name IN VARCHAR2) AS
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello ' || p_name || '! Welcome to Surat Academy.');
END;
/
π» 2. Working with Parameters (The 3 Modes) π οΈΒΆ
| Mode | Direction | Purpose |
|---|---|---|
| IN | Input π₯ | Passing data into the procedure (Read-only). |
| OUT | Output π€ | Returning a result back to the caller. |
| IN OUT | Both π | Passing a value in, changing it, and sending it back. |
Example: The Salary AdjusterΒΆ
CREATE OR REPLACE PROCEDURE adjust_salary(
p_emp_id IN NUMBER,
p_inc IN NUMBER,
p_new_sal OUT NUMBER -- π€ Return value
) AS
BEGIN
UPDATE employees SET salary = salary + p_inc
WHERE id = p_emp_id
RETURNING salary INTO p_new_sal;
END;
/
ποΈ Architect's Note: Performance & Security π‘οΈΒΆ
- Compilation: Procedures are compiled once. When you call them, they run instantly without the overhead of parsing SQL. β‘
- Security: You can give an intern permission to "EXECUTE" the
give_raiseprocedure without giving them "UPDATE" permission on theEMPLOYEEStable. This keeps your data safe. π - Abstraction: If you change the math inside the procedure, you don't have to update your Java or Python code. The app just gets the new result automatically.