35
CS348 – INFORMATION SYSTEMS Romila Pradhan PL/SQL

CS348 – INFORMATION SYSTEMS · - Oracle Corporation's procedural extension for SQL and the Oracle relational database ... -Basic unit of a PL/SQL program - Three possible sections

Embed Size (px)

Citation preview

CS348 – INFORMATION SYSTEMS

Romila Pradhan

PL/SQL

Introduction

PL/SQL stands for Procedural Language/SQL

- Oracle Corporation's procedural extension for SQL and the Oracle relational database

- Extends SQL by adding constructs found in procedural languages- Variables and types- Control Structures (conditional, loops)- Procedures and functions- Exception handling …

Advantages

- PL/SQL units such as procedures, functions, packages, types, and triggers, which are stored in the database for reuse by applications that use the Oracle Database interface

- Use in coding business rules and other procedural logic at database level- Enforcing integrity constraints/rules, e.g.,- referential integrity (insert data in another table whenever record inserted in one table)- update pay of employees within a range

- Batch routines (e.g., for creating forms/reports on millions of records)

Advantages

- SQL executes one statement at a time

- PL/SQL allows to group SQL statements logically and send them to Oracle in a block

- This reduces network traffic and processing overhead. Therefore, better performance

Basic Structure: Block-Basic unit of a PL/SQL program- Three possible sections of a block- Declarative section- Executable section- Exception handling

Basic Structure: Block-Basic unit of a PL/SQL program- Three possible sections of a block- Declarative section- Executable section- Exception handling

DECLARE/* Declarative section: variables, types, and local

subprograms. */

BEGIN/* Executable section: procedural and SQL statements go

here. */

/* This is the only section of the block that is required. */

EXCEPTION/* Exception handling section: error handling statements go

here. */

END;.run

Block: Executable Section- The ONLY required section

-Contains constructs such as assignments, branches, loops, procedure calls, and triggers

- SQL statements permitted in a PL/SQL program:- DML statements (e.g., SELECT, INSERT, UPDATE, DELETE)

-NOT permitted:- DDL statements (CREATE, DROP, ALTER)

Execution

Program statement followed by- a line with a single dot . ,and then- a line with run

DECLARE/* Declarative section: variables, types, and local

subprograms. */

BEGIN/* Executable section: procedural and SQL statements go

here. */

/* This is the only section of the block that is required. */

EXCEPTION/* Exception handling section: error handling statements go

here. */

END;.run

Variables, Types

9

Variables- To transmit information between a PL/SQL program and the

database- declared in the declaration section

Variables- To transmit information between a PL/SQL program and the

database- declared in the declaration section

- Associated type (same as used by SQL for database columns)- same as the type of some database column- generic type used in PL/SQL (NUMBER/VARCHAR(n)/BOOLEAN)

VariablesTo represent one field- same type as the column- use %TYPE instead of hardcoding- e.g., musicianPhone Musician.Phone%TYPE

VariablesTo represent one field- same type as the column- use %TYPE instead of hardcoding- e.g., musicianPhone Musician.Phone%TYPE

To represent a record with several fields- declared using %ROWTYPE on a relation name - e.g., tempMusician Musician%ROWTYPE

variable tempMusicians is a record with fields (MNO, Name, Address, Phone)

VariablesTo represent one field- same type as the column- use %TYPE instead of hardcoding- e.g., musicianPhone Musician.Phone%TYPE

To represent a record with several fields- declared using %ROWTYPE on a relation name - e.g., tempMusician Musician%ROWTYPE

variable tempMusicians is a record with fields (MNO, Name, Address, Phone)

- Initialized to NULL (regardless of the type)- Assign a value using the := operator

Control Flow

IF-ELSIF LOOPSIF <condition_1> THEN <statement_list>ELSIF <condition_2> THEN <statement_list>…ELSIF <condition_n> THEN <statement_list>ELSE <statement_list>END IF;

- Simple LoopLOOP

<loop_body>EXIT WHEN <condition>

END LOOP;

- Numeric For LoopFOR <var> IN <start> .. <finish> LOOP

<loop_body> EXIT WHEN <condition>

END LOOP;

- While LoopWHILE <condition> LOOP

<loop_body> EXIT WHEN <condition>

END LOOP;

Sample PL/SQL Program

-Create temporary tableTEMPMUSICIAN(tempNo INTEGER, tempName VARCHAR(24))

-Download from https://www.cs.purdue.edu/~rpradhan/cs348/s17/plsql_select.sql

Sample PL/SQL ProgramThings to note:- SELECT must be followed by INTO listing variables into which the components of the

retrieved tuple must be placed

- Printing on terminal- SET SERVEROUTPUT ON- DBMS_OUTPUT.PUT_LINE();

Execute the programSQL> @plsql_select

Check the changesSQL> SELECT * FROM TEMPMUSICIAN;

Sample PL/SQL Program

Edit the file:- WHERE MNO = 1 à WHERE MNO > 1

- SQL> @plsql_select

Sample PL/SQL Program

Edit the file:- WHERE MNO = 1 à WHERE MNO > 1- SQL> @plsql_selectMusician- Error

ERROR at line 1:ORA-01422: exact fetch returns more than requested number of rowsORA-06512: at line 6

Sample PL/SQL Program

Edit the file:- WHERE MNO = 1 à WHERE MNO > 1- SQL> @plsql_selectMusician- Error

ERROR at line 1:ORA-01422: exact fetch returns more than requested number of rowsORA-06512: at line 6

- SELECT statement works if the result of the query contains a single tuple

Cursors

- Variable that permits the program to run through the tuples of some relation which could be- a table, or- answer to a query

-Can read/process each such tuple fetched into the cursor

-Can update/delete the tuple at the current cursor position if the relation is stored

Sample Cursor Programs

- Iterating over cursor results- https://www.cs.purdue.edu/~rpradhan/cs348/s17/plsql_cursor.sql

Sample Cursor Programs

- Iterating over cursor results- https://www.cs.purdue.edu/~rpradhan/cs348/s17/plsql_cursor.sql

-Modifying base relation- Create temporary table: TEMPPERFORM(MNO INTEGER, SNO INTEGER,

INSTRUMENT VARCHAR(24));

- https://www.cs.purdue.edu/~rpradhan/cs348/s17/plsql_cursor_update.sql

Procedures

Procedures

- Similar to procedures/functions in other programming languages

CREATE [OR REPLACE] PROCEDURE P_Name(Parameters) AS <local variable declarations>BEGIN<procedure body>END;

.run;

- This . and run creates the procedure; to execute, invoke it in another PL/SQL program in the executable section

Sample ProcedurePrint the names of musicians who performed using a particular instrument (parameter -- instrument name)- Download at https://www.cs.purdue.edu/~rpradhan/cs348/s17/plsql_procedure.sql

- Create the procedure SQL> @plsql_procedure

- Execute the procedure SQL> BEGINMUSICIANS_PERFORMED_INSTRUMENT(‘Guitar’);END; .

SQL> run;

- (If you wish) Drop the procedure SQL> DROP PROCEDURE MUSICIANS_PERFORMED_INSTRUMENT;

Debugging Procedures

"procedure created with compilation errors”

If you don't see what is wrong immediately, try issuing the command - SQL> SHOW ERRORS ….....to see the most recent compilation error.- SQL> SHOW ERRORS PROCEDURE <procedure_name>;

- Note that location of the error in the error message is not always accurate!

Triggers

Triggers

- Special PL/SQL constructs similar to procedures

- A procedure is executed explicitly from another block via a procedure call

- A trigger is executed implicitly whenever the triggering event happens

Triggers

Triggering event - INSERT, DELETE, UPDATE

Timing - Before / After

Level:- row-level: fires once for each row affected by the statement - statement-level: fires once for the whole statement

Triggers -- construct

CREATE [OR REPLACE] TRIGGER <trigger_name>{BEFORE|AFTER} {INSERT|DELETE|UPDATE} ON <table_name> [REFERENCING [NEW AS <new_row_name>] [OLD AS <old_row_name>]] [FOR EACH ROW [WHEN (<trigger_condition>)]]

<trigger_body>

Triggers

May specify up to three triggering events using the keyword OR. e.g., ... INSERT OR DELETE OR UPDATE ON R ...

UPDATE can be optionally followed by the keyword OF and a list of attribute(s) in <table_name>. - e.g., ... UPDATE OF A, B OR INSERT ON R ... - the OF clause defines the event to be only an update of the attribute(s)

listed after OF

Trigger restrictions

Oracle restrictions to avoid situations where one trigger performs an action that triggers a second trigger, which then triggers a third, and so on, which could potentially create an infinite loop:

- Cannot modify the same relation whose modification is the triggering event

- Cannot modify a relation connected to the triggering relation by another constraint (such as a foreign-key constraint)

Sample trigger programGet the trigger program from https://www.cs.purdue.edu/~rpradhan/cs348/s17/plsql_trigger.sqlSQL> @plsql_trigger …..... will create (and enable) the trigger

Now insert a record that would trigger the event. Check the contents of the concerned table to see changes.

Enabling/disabling the triggerSQL> ALTER TRIGGER <trigger_name> ENABLE/DISABLE

Dropping the triggerSQL> DROP TRIGGER <trigger_name>;(Dropping the triggering table also drops the trigger)