Database Systems Lecture 3
DATABASE SYSTEMS
Lecture 3
Previous Lecture Overview
Features of Oracle SQL
Types
Aliases
Join operations
Hierarchical traversal of a table containing a recursive relation
View tables and DML (Data Manipulation Language) operations through view tables
Upper-N analysis
Characteristics of the PL/SQL Language
Instruction blocks
Variable types
Record type
Control structures
Using cursors
Exception handling
Using an Explicit Cursor
Example 1
Cursor Declaration:
DECLAREdepartment employees.department_id%TYPE;f NUMBER(5);CURSOR department_cur IS SELECT department_id, COUNT(*) FROM employees GROUP BY department_id;
Begin Block:
BEGIN ... END;
Example 2
Explicit Cursor Syntax:
DECLARE...BEGINOPEN department_cur;FETCH department_cur INTO department, f;WHILE department_cur%FOUND LOOPDBMS_OUTPUT.PUT_LINE('departmentID: ' || department || ' staff: ' || f);FETCH department_cur INTO department, f;
END LOOP;END;
Using an Explicit Cursor (Advanced)
Cursor Declaration:
DECLARECURSOR department_cur IS SELECT department_id AS r, COUNT(*) AS lsz FROM employees GROUP BY department_id;r_rec department_cur%ROWTYPE;
Begin Block:
BEGINFOR r_rec IN department_cur LOOPDBMS_OUTPUT.PUT_LINE('departmentID: ' || r_rec.r || ' staff: ' || r_rec.lsz);
END LOOP;END;
Differences Between Cursor Modes
Version 1:
Requires a separate variable for each field.
Version 2:
Uses a record that corresponds to the row type; all fields must be named (original field name or alias).
No need to open the cursor and fetch a record in advance; simpler syntax using a record.
Cursor Attributes
%FOUND: True if the last operation (e.g., FETCH) found a record.
%NOTFOUND: True if there was no record to process.
%ROWCOUNT: Number of rows fetched from the cursor so far; not an attribute but represents affected rows after a DML command (
SQL%ROWCOUNT).%ISOPEN: False if the cursor is not opened (always false for an implicit cursor).
Explicit Cursor for Individual Operations
Creation of cursor with FOR UPDATE clause allows modification/deletion of the examined record.
FOR UPDATE locks the rows in the result set to indicate that they may change.
NOWAIT: System does not wait for locked rows.
CURRENT OF cursor name: Identifies the currently examined record.
Example of Using FOR UPDATE
Context: Increase salaries of IT_PROG employees by 20%.
CREATE TABLE worker AS SELECT * FROM employees;
DECLARE
CURSOR worker_cur IS SELECT employee_id, last_name, salary FROM worker WHERE job_id='IT_PROG' FOR UPDATE NOWAIT;
id worker.employee_id%TYPE;
name worker.last_name%TYPE;
pay worker.salary%TYPE;
BEGIN
OPEN worker_cur;
LOOP
FETCH worker_cur INTO id, name, pay;
EXIT WHEN worker_cur%NOTFOUND;
pay := pay * 1.2;
UPDATE worker SET salary = pay WHERE CURRENT OF worker_cur;
DBMS_OUTPUT.PUT_LINE(name || ': ' || pay);
END LOOP;
CLOSE worker_cur;
END;
Exception Handling in PL/SQL
Definition: An event with an identifier that interrupts the block of code.
User-Defined Exceptions:
Can be declared with
DECLARE exception_name EXCEPTION;Triggered using
IF boolean_expression THEN RAISE exception_name;
Predefined System Exceptions
These exceptions are triggered by the runtime system.
User exceptions can be associated with system ones during declaration:
DECLARE
exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT(exception_name, errorcode);
PRAGMA: A compiler directive not included in executable code.
Example Handling Code
BEGIN ... EXCEPTION
WHEN No_Data_Found THEN message;
WHEN Too_Many_Rows THEN message;
WHEN Others THEN message;
END;
Error code and message available in:
SQLCODE,SQLEERRM.
PL/SQL - Subroutines
Subroutine: A named, parameterizable instruction block.
Procedure: A subroutine primarily executed for side effects (e.g., statements, data changes, DDL instructions); no return value but can have output parameters.
Function: Subroutine that returns a value; preferred to avoid using outgoing parameters.
Syntax for Procedure
PROCEDURE name [(par1 [, par2]...)] {IS|AS} [local declarations (without DECLARE)]
BEGIN
instructions to be executed
[EXCEPTION exception handling]
END [name];
Syntax for Function
FUNCTION name [(par1 [, par2]...)] RETURN data_type {IS|AS} [local declarations (without DECLARE)]
BEGIN
instructions to be executed
RETURN return_value
[EXCEPTION exception handling]
END [name];
Parameters Syntax (both Procedures and Functions)
Defined as:
par_name [IN|OUT|IN OUT] data_type [{DEFAULT|:=} expression];IN: Input parameter; its value cannot be changed in the subprogram.
OUT: Can only receive but not provide value.
IN OUT: Can both receive and provide a value within the subroutine.
expression: Initializes a value (only for IN and IN OUT parameters).
Data Types of Parameters
Types must be known, but restrictions (length, accuracy) may not be enforced.
Examples include: NUMBER, INTEGER, REAL, CHAR, VARCHAR2.
References can be used (
%TYPE,%ROWTYPE); functions recommended to use onlyINtype.
Year-End Bonus Example
Context: Workers earning below $3000 receive a 10% bonus.
Table Creation: To store employee ID, last name, and bonus amount.
CREATE TABLE Premiums (
employee_id NUMBER(6,0) PRIMARY KEY,
last_name VARCHAR2(25),
premium NUMBER(8,2)
);
Program Structure
Requesting Employee ID:
ACCEPT worker_id PROMPT 'The worker's ID: ';
DECLARE
...
BEGIN
...
END;
Handle incorrect IDs, workers with high/sufficient salaries, and bonuses.
Subroutine Declarations
PROCEDURE Reward(
p_id IN employees.employee_id%TYPE,
p_lname OUT employees.last_name%TYPE,
p_prem OUT employees.salary%TYPE
) IS
...
END Reward;
Subroutine Body Example
BEGIN
SELECT first_name, last_name, salary INTO p_fname, p_lname, p_sal
FROM employees WHERE employee_id=p_id;
IF p_sal >= 3000 THEN
RAISE No_Reward;
END IF;
p_prem := 0.1 * p_sal;
DBMS_OUTPUT.PUT_LINE(p_fname || ' ' || p_lname || ' reward: ' || p_prem || ' USD');
END Reward;
Exception Handling in Subroutine
BEGIN
...
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('There is no such worker!');
WHEN No_Reward THEN
DBMS_OUTPUT.PUT_LINE('Merry Christmas dear ' || p_fname || '!');
END Reward;
Main Program Body Example
BEGIN
v_id := &worker_id;
Reward(v_id, v_lname, v_prem);
IF v_prem IS NOT NULL THEN
INSERT INTO Premiums VALUES(v_id, v_lname, v_prem);
END IF;
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('Previously recorded.');
END;
Stored Subroutines
Non-Stored Subroutines: Only accessible from the statement block that calls them, limited reuse.
Access: Users can call stored subroutines from any statement block, enhancing visibility (with permissions).
Creating Stored Procedures
CREATE OR REPLACE PROCEDURE name [(par1 [, par2]...)] [AUTHID {DEFINER | CURRENT_USER}] {IS|AS} [PRAGMA AUTONOMOUS_TRANSACTION;] [local declarations (without DECLARE)]
BEGIN
instructions to be executed
[EXCEPTION exception handling]
END [name];
AUTONOMOUS_TRANSACTION: Indicates the subroutine runs independently.
Deleting Stored Subprograms:
DROP PROCEDURE procedure_name;
DROP FUNCTION function_name;
Error Handling with RAISE_APPLICATION_ERROR
Functionality: Displays user-defined and predefined error messages.
RAISE_APPLICATION_ERROR(error code, message);
Code Range: -20000 to -20999.
Running Stored Routines
Stored Procedure:
EXECUTE [user].procedure_name(parList);
EXEC [user].procedure_name(parList);
Stored Function: Returned value must be used as part of an instruction block.
BEGIN
DBMS_OUTPUT.PUT_LINE(function_name(parLista));
END;
Triggers
Definition: A program automatically activated by specific events.
Triggers start automatically as a result of events; user cannot influence the activation.
Triggers should not contain
COMMITorROLLBACKapart fromPRAGMA AUTONOMOUS_TRANSACTION.
Trigger Events
DML statements (DELETE, INSERT, UPDATE)
DDL statements (CREATE, ALTER, DROP)
System events (database startup, shutdown, error messages)
User events (user creation, entry, exit)
Application of Triggers
Purpose:
Protect database integrity
Record changes in the database
Triggers help to:
Enforce user specifications
Prevent invalid transactions
Automatically generate derived attribute values
Synchronize data tables
Log events
Collection of Triggers
Importance in mapping triggers due to trigger chaining.
To list stored objects associated with the user:
SELECT object_type, object_name FROM user_objects WHERE object_type IN ('PROCEDURE', 'FUNCTION', 'TRIGGER');
Query trigger headers:
SELECT description FROM user_triggers;
Trigger source code queries:
SELECT line, text FROM user_source WHERE name = 'trigger_name';
Creating a Trigger
CREATE [OR REPLACE] TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] trigger_event [OR trigger_event] ON {data_table|view table} [FOR EACH ROW [WHEN condition]] [DECLARE list of local variables]
BEGIN
instructions [exception handling]
END;
Additional Considerations for Triggers
Triggering event tied to a DML command e.g.,
{DELETE|INSERT|UPDATE [OF column]}.If a column name is after
UPDATE, only fires for that specific column.FOR EACH ROW: Executes the trigger on all affected rows.
Statement-level: Fires even if the operation doesn't affect records.
Trigger Examples
Example 1
Create a trigger to prevent DML commands on the employees table outside working hours.
CREATE OR REPLACE TRIGGER No_working_hours BEFORE INSERT OR DELETE OR UPDATE ON employees
BEGIN
IF TO_CHAR(sysdate, 'HH24:MI') NOT BETWEEN '08:00' AND '16:00' THEN
RAISE_APPLICATION_ERROR(-20111, 'Can be used only between 8 and 16!');
END IF;
END;
Check the Trigger
Attempt insertions during restricted hours.
Example 2: Trigger for Region Insert Logging
Create a trigger that logs when a new record is inserted for regions. The insertions go to a logging table, not the original.
CREATE TABLE regions_1 AS SELECT * FROM regions;
ALTER TABLE regions_1 ADD CONSTRAINT regio_pk PRIMARY KEY(region_id);
Prepare the Logging Table
CREATE TABLE regions_log (
insert_date DATE,
username VARCHAR2(100),
region_id NUMBER,
region_name VARCHAR2(25)
);
Trigger to Log Insertion Attempts
CREATE OR REPLACE TRIGGER region_insert BEFORE INSERT ON regions_1 FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO regions_log VALUES(sysdate, user, :new.region_id, :new.region_name);
COMMIT;
END region_insert;
Packages in PL/SQL
Facilitates joint management of related subprograms, enhances reusability, and eases review in large databases.
Built-in packages include: DBMS_OUTPUT, UTL_FILE, UTL_HTTP.
Creating Your Own Package
Interface Translation: Only subprograms specified are accessible externally.
Implementation Translation: Must be expanded to include all subroutines.
Creating the Interface
CREATE OR REPLACE PACKAGE package_name IS
PROCEDURE procedure1name(parList);
PROCEDURE procedure2name(parList);
FUNCTION function1name(parList) RETURN return_value_type;
END package_name;
Creating the Body of the Package
CREATE OR REPLACE PACKAGE BODY package_name IS
PROCEDURE procedure1name(parList) IS [local declarations]
BEGIN ... END procedure1name;
END package_name;
Using Package Subroutines
Example calls to procedure and function within a block:
BEGIN
package_name.procedure1name(actParList);
DBMS_OUTPUT.PUT_LINE(package_name.function1name(actParList));
END;
Package Example: emp_mgmt
Functionality:
hire: Inserts employee and returns newemployee_id.remove_emp: Deletes employee by ID.increase_sal: Increases employee salary by specified amount.Maintains current number of employees.
Creating the Package Interface and Body
Interface:
CREATE OR REPLACE PACKAGE emp_mgmt AS
FUNCTION hire(first_name VARCHAR2, last_name VARCHAR2, job_id VARCHAR2, manager_id NUMBER, salary NUMBER, commission_pct NUMBER, department_id NUMBER) RETURN NUMBER;
PROCEDURE remove_emp(employee_id NUMBER);
PROCEDURE increase_sal(employee_id NUMBER, salary_incr NUMBER);
no_emp EXCEPTION;
no_sal EXCEPTION;
END emp_mgmt;
Body:
CREATE OR REPLACE PACKAGE BODY emp_mgmt AS
tot_emps NUMBER;
BEGIN
SELECT count(*) INTO tot_emps FROM employees;
END emp_mgmt;
Subprograms:
Entry function, deletion procedure, salary increase procedure.
Conclusion
This lecture covers substantial topics in PL/SQL, focusing on explicit cursors, exception handling, subroutines, triggers, and package management related to Oracle SQL.