PL-SQL Stored Procedures and Functions

Context: FIT3003_MOC Β· the W11 PL/SQL Revision deck Β· the language every trigger in Active Data Warehousing is written in Β· the third stored object βž” Database Triggers (Oracle) Β· the cursor-loop route also appears in Junk Dimensions Parent Framework: SQL Sublanguages (DDL, DML, DCL)

Quick Revision

  • 🎯 Objective: PL/SQL groups SQL statements with procedural syntax (variables, IF, loops, cursors) in a DECLARE … BEGIN … END; block βž” stored as a named schema object: a procedure (a statement on its own), a function (part of an expression, returns a value) or a trigger (fired by DML).
  • πŸ“¦ Core Components: IN βž” read only | OUT βž” write only | IN OUT βž” both.
  • ⚑ Key Constraint: SELECT … INTO must find exactly one row βž” none raises NO_DATA_FOUND, which ends the block unless an EXCEPTION handler catches it.

πŸ“ How It Works

1. The block

  • Shape βž” DECLARE locals Β· BEGIN body Β· optional EXCEPTION WHEN … THEN Β· END;.
  • Assignment βž” v_Counter := 7; β€” := assigns, = compares.
  • Anchored type βž” v_Firstname student.first_name%type follows the column if it is retyped (VARCHAR2(20) βž” VARCHAR2(25)); a hard-coded VARCHAR2(20) would truncate or fail. Syntax: <variable> <table>.<column>%type.
  • Debug output βž” dbms_output.put_line('Data inserted …'); prints only after SQL> set serveroutput on;.
  • Body contents βž” IF-THEN-ELSE, loops, cursor fetching, and INSERT / UPDATE / DELETE.

2. Control flow

  • Branch βž” IF c THEN … ELSIF c THEN … ELSE … END IF; (a nested IF inside ELSE is equivalent).
  • Simple loop βž” LOOP … IF v_Counter > 50 THEN EXIT; END IF; END LOOP; β€” the exit test is yours to write.
  • While loop βž” WHILE v_Counter <= 50 LOOP … END LOOP; β€” tested before each pass.

3. Cursors

  • Context area βž” memory Oracle allocates per statement: rows processed, a pointer to the parsed statement, and for a query the active set (its result rows).
  • Cursor βž” a handle (pointer) to that context area, declared as CURSOR c IS SELECT …; among the locals; it may use the procedure’s parameters in its WHERE.
  • Cursor FOR loop βž” FOR rec IN c LOOP … rec.column … END LOOP; β€” one pass per active-set row; rec is not declared.

4. Stored procedures

  • What βž” a self-contained schema object grouping SQL statements to perform one specific task; called with parameters, it acts, then returns to the caller.
  • Header βž” CREATE [OR REPLACE] PROCEDURE name (p [IN | OUT | IN OUT] type, …) AS β€” locals sit between AS and BEGIN, no DECLARE; parameters may be anchored (p_ID students.id%TYPE).
  • Run / remove βž” EXECUTE name(args); Β· DROP PROCEDURE name;.
  • Design rules βž” one focused task per procedure; never duplicate functionality the database language already provides.

5. Stored functions

  • Header βž” CREATE [OR REPLACE] FUNCTION name (…) RETURN type IS locals BEGIN … RETURN value; END name;.
  • Call site βž” a procedure call is a statement by itself; a function call sits inside an expression β€” a SELECT list (SELECT department, ClassInfo(department, course) FROM classes;) or an IF test in another block.
  • RETURN βž” hands control back to the caller with a value; the first one reached ends the function.

6. Data dictionary

  • List βž” SELECT * FROM user_objects WHERE object_type = 'PROCEDURE'; Β· source βž” user_source Β· compile errors βž” user_errors, each filtered WHERE name = '…'.

βš™οΈ Core Implementation

πŸ”Ή Parameter modes β€” ModeTest

πŸ”Ή Exception as control flow β€” credit_account

πŸ”Ή Cursor loop inside a procedure β€” CheckStudentCompletion

πŸ”Ή Function and its caller β€” ClassInfo

βš–οΈ Core Decision Matrix

ObjectInvoked byHeaderHands backTypical job
Procedurean explicit call β€” EXECUTE, or a statement in another blockCREATE PROCEDURE … ASOUT / IN OUT parametersone focused task (AddNewStudent)
Functionan expression β€” a SELECT list, an IF testCREATE FUNCTION … RETURN type ISone value via RETURNa computed value or label per row (ClassInfo)
Triggerthe system, on INSERT / UPDATE / DELETE of its tableCREATE TRIGGER … {BEFORE | AFTER | INSTEAD OF} … ON tnothing β€” acts through DMLenforce rules, maintain derived tables βž” Database Triggers (Oracle)
ModeCaller passesBody may readBody may write
INa valueβœ…βŒ
OUTa variable to fill❌ (per the slides)βœ…
IN OUTan initialised variableβœ…βœ…

When It Flips: need the result inside a query βž” function; need several results, or the work itself is the point βž” procedure with OUT parameters; no one should have to remember to call it βž” trigger.

πŸ“Š Exam Execution Trace & Applied Exercises

Manual Execution Trace β€” ClassInfo boundaries ()

current_studentsFirst true branchReturns
'Full'
'Some Room'
β€” is not 'More Room'
β€” is not 'Lots of Room'
ELSE'Empty'
  • Boundary reading βž” strict > sends an exact or down a band; ELSIF stops at the first true test, so order the tests from the highest threshold down.

⚠️ Common Mistakes

  • πŸ’‘ DECLARE inside a procedure or function βž” their locals go after AS / IS; DECLARE belongs to anonymous blocks and triggers.
  • πŸ’‘ Unquoted object_type = PROCEDURE βž” the slide’s form is read as a column name and fails; quote it: 'PROCEDURE'.

🧠 Active Recall