100% found this document useful (2 votes)
307 views

Oracle PL SQL

PL/SQL provides a programming facility for Oracle users to implement complex business logic. The module covers PL/SQL fundamentals including features, block structures, identifiers, variables, data types, composite types, statements, expressions, conditional and loop constructs. PL/SQL extends SQL with features like variables, control structures, procedures, functions and object types to add procedural functionality.

Uploaded by

ramnandesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
307 views

Oracle PL SQL

PL/SQL provides a programming facility for Oracle users to implement complex business logic. The module covers PL/SQL fundamentals including features, block structures, identifiers, variables, data types, composite types, statements, expressions, conditional and loop constructs. PL/SQL extends SQL with features like variables, control structures, procedures, functions and object types to add procedural functionality.

Uploaded by

ramnandesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 137

Oracle PL/SQL Training

2.0 PL/SQL Fundamentals : Overview

Introduction:
PL/SQL provides programming facility to the users in
Oracle to implement complex business logic.

Objective:
After completing this module, you will be able to,
1 .PL/SQL Features
2. PL/SQL Block Structures
3. Identifiers
4. Variables
5. Data Types
2.0 PL/SQL Fundamentals : Overview

6. Composite Types
7. PL/SQL Statements
8. PL/SQL statements
9. Oracle Supplied Packages
10. Expressions and Operators
11. Conditional and Loop Constructs
PL/SQL Features

Features of PL/SQL

PL/SQL stands for Procedural Language/SQL


PL/SQL extends SQL by adding constructs found
in other procedural languages
Variables and types
Control Structures (IF-THEN-ELSE)
Procedures and Functions
Object types and methods
PL/SQL Features

Difference between SQL and PL/SQL

SQL Statement
SQL> SELECT sysdate FROM DUAL;
PL/SQL Statement
DECLARE
l_date DATE;
BEGIN
SELECT sysdate into l_date from dual;
END;
PL/SQL Features

Need of PL/SQL
Procedural Language/Structured Query Language
is an extension to SQL

PL/SQL provides programming facility to the


users

Set of instructions that can be stored in the


server as Database Objects in compiled form
PL/SQL Features

How Pl/SQL Works


Blocks of Pl/SQL statements are translated by the
PL/SQL engine that can reside either in the client
or at the server side

It divides the SQL statements from PL/SQL block


and sends them to SQL STATEMENT EXECUTOR

The output finally comes to the Client end


PL/SQL Features

PL/SQL Architecture
PL/SQL Features

PL/SQL Architecture
PL/SQL Block Structure

PL/SQL is a block structured language

PL/SQL program is made up of a series of


statements. A statement is terminated with a
semicolon (;), not with the physical end of a line

It has three parts, Declarative part, an


Executable part and an Exception Handling part
PL/SQL Block Structure

Syntax

DECLARE
/*Declarative Section - PL/SQL variables,
cursors and types */
BEGIN
/* Executable section - procedural and SQL statements */
EXCEPTION
/* Exception handling section - error handling statements */
END;
PL/SQL Block Structure

Anonymous Blocks
Declare
/* variables*/
Begin
/*SQL statements */
Exception
/* Error handling */
End;
PL/SQL Block Structure

Named Block
Replace DECLARE keyword with CREATE OR REPLACE
Example
Create or Replace Procedure Validate_Date AS
/* variables*/
Begin
/*SQL statements */
Exception
/* Error handling */
End Validate_Date;
Identifiers

Must start with a letter

Up to 30 characters in length

May include a $ (dollar sign), _ (underscore),


and # (pound sign)

Cannot contain embedded spaces


Variables

Variables are memory locations, which can store data values

Information from database can be assigned to a variable, or


the contents of a variable can be inserted into the database

The variables are declared in the declarative section of the


block

Every variable has a specific type which describes what kind


of information it can store
Variables

Variable Declarations

Declaration Syntax
variable_name type [CONSTANT][NOT NULL][:=value]
Example
DECLARE
v_Description VARCHAR2(50);
v_NumberSeats NUMBER := 45;
v_Counter BINARY_INTEGER DEFAULT 0;
Variables

Variable Scope

DECLARE
v_number NUMBER(3,2);
BEGIN

Scope of DECLARE
v_number v_Character VARCHAR2(10);
Scope of
BEGIN
v_Character

END;
END;
Data Types

Data Types Scalar Datatypes


BINARY_INTEGER
DEC CHAR
DECIMAL CHARACTER
DOUBLE PRECISION LONG
FLOAT LONG RAW
INT ROWID
INTEGER STRING
NATURAL VARCHAR
NUMBER VARCHAR2
NUMERIC
POSITIVE
REAL DATE BOOLEAN
SMALLINT

Composite Records PL/SQL


Dataypes Tables
Composite Types

PL/SQL Record

A record is similar to “C” structure


Record provide a way to deal with separate but
related variables as Unit
To use, developer must define the type, then declare
variables of that type
To refer to a field within a record , dot notation is
used
Composite Types

PL/SQL Record
Following declarative section can be replaced by PL/SQL
Record
Example
DECLARE
v_StudentID NUMBER(5);
v_FirstName VARCHAR2(20);
v_LastName VARCHAR2(20);
DECLARE
TYPE t_studentRec IS RECORD (
StudentID NUMBER(5),
FirstName VARCHAR2(20),
LastName VARCHAR2(20));
v_studentInfo t_StudentRec;
Composite Type

PL/SQL Record

Use the %ROWTYPE attribute to declare a record based upon a


collection of database columns from a table or view
The fields within the record take their names and data types from the
columns of the table or view
Declare the record in the DECLARE section along with any other
required variables and constants
Example
DECLARE
REC1 EMP%ROWTYPE;
REC2 EMP%ROWTYPE
Composite Type

PL/SQL Table

A table is like “C” array


Syntax
Type array_name is TABLE OF data_type
INDEX BY BINARY_INTEGER;
t_temp array_name;
 Data type can be
varchar2, Number, Table.column%TYPE, Table%Rowtype

Example
TYPE string_name IS
TABLE OF VARCHAR2(30)
INDEXED BY BINARY_INTEGER;
employee_name_table string_name;
Composite Type

PL/SQL Table
The number of rows in a Pl/SQL table can
increase dynamically

A Table can have only one primary


key(BINARY_INTEGER) and a column

The individual element in the PL/SQL table is


accessed by tablename(index)
Composite Type

table.count : Return number of rows

table.delete : Remove from PL/SQL table

table.delete(i) : Remove i th row from PL/SQL table

table.FIRST: Return the index of the first row

table.LAST : Return index of the last row


PL/SQL Statements

Statements in PL/SQL

The INTO clause must be used to store a table column value


into a variable declared in the DECLARATION section of
PL/SQL block
SELECT ENAME INTO MEMNAME FROM EMP WHERE
EMPNO=101176;

Multiple column values can be assigned to equal number of


memory variables using single INTO
SELECT ENAME, SAL INTO MEMNAME, MEMSAL FROM EMP WHERE
EMPNO=101176;
Oracle Supplied Packages

Packaged procedures are supplied with Oracle to enable


PL/SQL access SQL features or enhance the functionality of
the database

The names of the packages are


 DBMS_ALERT
 DBMS_DDL
 DBMS_DESCRIPTION
 DBMS_JOB
 DBMS_LOCK
 DBMS_OUTPUT
Expressions and Operators

An expression is a sequence of variables and literals, separated by


operators.
The most basic operator is assignment
Syntax
variable := expression
Variable is PL/SQL variable and expression is PL/SQL expression
PL/SQL expression is: 3 + 5 * 7
Concatenation operator ( || ) attaches two or more strings together.
For example , the expression ‘Hello ’||’World’ evaluates to ‘Hello
World’.
Expressions and Operators
Conditional and Loop Constructs

PL/SQL Control Structures

IF-THEN-ELSE
LOOPS
WHILE LOOPS
FOR LOOPS
Conditional and Loop Constructs

IF-THEN-ELSE

Syntax
IF boolean_statements1 THEN
sequence_of_statements1;
ELSIF boolean_statements2 THEN
sequence_of_statements2;
ELSE
sequence_of_statements3;
END IF;
Conditional and Loop Constructs

Example

DECLARE
v_NumberSeats rooms.number_seats%TYPE;
v_Comment VARCHAR2(35);
BEGIN
/* Retrieve the number of seats in the room
identified by ID 99999.
Store the result in v_NumberSeats. */
SELECT number_seats
INTO v_NumberSeats
FROM rooms
WHERE room_id = 99999;
Conditional and Loop Constructs

IF v_NumberSeats < 50 THEN


v_Comment := 'Fairly small';
ELSIF v_NumberSeats < 100 THEN
v_Comment := 'A little
bigger';
ELSE
v_Comment := 'Lots of room';
END IF;
END;
/
Conditional and Loop Constructs

LOOPS

Syntax
LOOP
sequence_of_statements;
END LOOP;
sequence of statements will be executed infinitely,since the loop has no
stopping condition. So, to break the loop the syntax is:
EXIT [WHEN condition];
Conditional and Loop Constructs

WHILE Loop

Syntax
WHILE condition LOOP
sequence_of_statements;
END LOOP;
Conditional and Loop Constructs

FOR Loop

Syntax
FOR loop_counter IN [REVERSE] low_bound .. high_bound LOOP
sequence_of_statements;
END LOOP;

Example
BEGIN
FOR v_counter IN 1 .. 50 LOOP
INSERT INTO temp_table values (v_counter,’Loop Index’);
END LOOP;
END;
PL/SQL Fundamentals : Summary

PL/SQL extends SQL by adding constructs found in other procedural


languages like conditional constructs, looping, variables data types,
procedures, functions etc.

Data types can be Scalar types and Composite types.

Composite Types can be PL/SQL Record and PL/SQL Tables

A Record is like a ‘C’ structure. The %ROWTYPE attribute is used to declare a


record based upon a collection of database columns from a table or view

A table is like a ‘C’ array. A Table can have only one primary
key(BINARY_INTEGER) and a column
: Quiz

Write a PL/SQL block to print the Department wise


Employee Details, with Total for each department as
well as Grand Total. The report should look like this,

DEPT No: 10 dname: Accounts


Deptno Emono Ename Job Sal
--- --- --- --- --
--- --- --- --- --
Total for Deptno 10
3.0 Cursors and Exceptions : Overview

Introduction:
A SQL cursor is a private Oracle SQL working area. The implicit cursor
is used by Oracle server to test and parse the SQL statements and the
explicit cursors are declared by the programmers. Oracle exceptions
handlers are used to trap runtime errors.

Objective:
After completing this module, you will be able to,
1 .Understand Cursors
2. Open Cursors
3. Fetch Cursor
4. Close Cursor
5. Cursor Attributes
3.0 Cursors and Exceptions : Overview

6. Examples of Cursors
7. Understand Exceptions
8. Pre-defined Exception
9 User-defined Exceptions
10. PRAGMA EXCEPTION_INIT
11. RAISE_APPLICATION_ERROR
Cursors

The cursor is a handle or pointer to the context area. The


context area is a memory allocation that Oracle allocate to
process a SQL statements
Cursor Types
 Implicit
 Explicit
An Implicit cursor is used for all other SQL statements
Implicit Cursors gives less programmatic control
In explicit cursor the cursor name is explicitly attached to a
select statement
Cursors

The four PL/SQL steps necessary for explicit


cursor processing are as follows:
Declare the cursor
Open the cursor
Fetch the results into PL/SQL variables
Close the cursor
Declaring a Cursor

 To use a cursor, it must be declared first


 Syntax
CURSOR cursor_name IS SELECT_statement;

 A cursor without parameters


CURSOR comp IS SELECT compid FROM company;

 A cursor with parameters


CURSOR comp (mcompid IN NUMBER) IS SELECT name FROM
company WHERE compid = mcomid;
Declaring a Cursor

Parameterized Cursors

A parameterized cursor takes arguments.


Example
DECLARE
CURSOR Class_cur ( i_dept classes.department%TYPE,
i_course classes.course%TYPE ) IS
SELECT * FROM CLASSES
WHERE department = i_department
and course = i_course;
Opening a Cursor

 When a Cursor is opened, PL/SQL executes the query for the cursor
 Syntax
OPEN cursor_name;

 A cursor can only be opened if it is closed


IF NOT Stud_cur%ISOPEN THEN
OPEN Stud_cur;
END IF;

 The following things happen if the cursor is opened:


 The values of the bind variables are examined
 Based on the bind variable the active set is determined
 The active set pointer is set to the first row.
Fetching Cursor

Fetching from a Cursor


It has two forms,
FETCH cursor_name INTO list_of_variables;
or
FETCH cursor_name INTO PL/SQL_record;
After each FETCH, the active set pointer is increased to next row

Thus, each FETCH will return successive rows in the active set, until the
entire set is returned.

The %NOTFOUND attribute is used to determine when the active set has
been retrieved.
Closing a Cursor

It tell PL/SQL that the program is finished with


the cursor, and the resource associated with it
can be freed
Syntax
CLOSE cursor_name;
Cursor Attributes

%FOUND : TRUE if the FETCH return rows, otherwise FALSE.

%NOTFOUND : TRUE if the FETCH doesn’t return rows,


otherwise FALSE.

%ROWCOUNT : Return the number of rows fetched by the


cursor so far

%ISOPEN : Returns TRUE if the cursor is open


Cursor Example

DECLARE
/* Output variables to hold the results of the query */
v_StudentID students.id%TYPE;
v_FirstName students.first_name%TYPE;
v_LastName students.last_name%TYPE;

/* Bind variable used in the query */


v_Major students.major%TYPE := 'Computer
Science';

/* Cursor declaration */
CURSOR c_Students IS
SELECT id, first_name, last_name
FROM students
WHERE major = v_Major;
Cursor Example

BEGIN
/* Identify the rows in the active set, and prepare for further
processing of the data */
OPEN c_Students;
LOOP
/* Retrieve each row of the active set into PL/SQL variables
*/
FETCH c_Students INTO v_StudentID, v_FirstName, v_LastName;

/* If there are no more rows to fetch, exit the loop */


EXIT WHEN c_Students%NOTFOUND;
END LOOP;

/* Free resources used by the query */


CLOSE c_Students;
END;
/
Exceptions

Oracle raises ERRORS whenever any abnormal


situation arises in a PL/SQL block and
performs an illegal termination of the
execution of the program

PL/SQL traps and responds to errors using an


architecture of EXCEPTION handler
Exceptions

Occurrence of any error in PL/SQL, whether a system error


or an application error, an exception is raised

This halts the processing in the current PL/SQL block's


execution and control is transferred to the separate
exception section of the program, if one exists, to handle the
exception

The control never returns to that block after you finish


handling the exception. Instead, control is passed to the
enclosing block, if any
Exceptions

When an exception is raised , control passes to the


exception section of the block. The exception section
consists of handlers for all the exceptions
EXCEPTION
WHEN exception_name THEN
sequence_of_statements1;
WHEN exception_name THEN
sequence_of_statements1;
END;
Exceptions

Exceptions types,
Predefined Exception

User Defined Exception


Predefined Exceptions

Some exceptions are already defined in Oracle called the predefined


exception

Mostly they are generated with the SELECT statement

They are raised implicitly at runtime

Every exception is associated with a error code

These exceptions are already defined in the STANDARD package (an Oracle
supplied package)

The when clause is used to test a system defined exception


Predefined Exceptions

 CURSOR_ALREADY_OPEN (ORA –  PROGRAM_ERROR(ORA-06501)


6511)
 ROWTYPE_MISMATCH(
 DUP_VAL_ON_INDEX( ORA-00001)
 STORAGE_ERROR(ORA-06500)
 INVALID_CURSOR(ORA-01001)
 TIMEOUT_ON_RESOURCE(ORA-
 INVALID_NUMBER(ORA-01722) 00051)

 LOGIN_DENIED(ORA-1017)  TOO_MANY_ROWS(ORA-01422)

 NO_DATA_FOUND(ORA-01403)  VALUE_ERRORS(ORA_06502)

 NOT_LOGGED_ON(ORA-01012)  ZERO_DIVIDE(ORA-01476)
Predefined Exceptions

Exception Functions
SQLCODE : Returns the numeric value for the error code

SQLERRM : Returns the message associated with the error number

Example
DECLARE
V_ERR_CODE NUMBER;
V_ERR_TEXT VARCHAR2(255)
EXCEPTION
WHEN NO_DATA_FOUND THEN
V_ERR_CODE := SQLCODE;
V_ERR_TEXT := SQLERRM;
Predefined Exceptions

Example

DECLARE
MEMNAME EMP.ENAME%TYPE;
BEGIN
SELECT ENAME INTO MEMNAME FROM EMP
WHERE EMPNO = &INPUT_EMPNO;
DBMS_OUTPUT.PUT_LINE(MEMNAME);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘No Such Employee’);
END;
User Defined Exception

Oracle allows user to raise their own exception in PL/SQL


block. Such exceptions are called User Defined Exception

They are to be declared in the Declaration Section and


should be explicitly raised using the RAISE statement

Syntax
DECLARE
e_TooManyStudents EXCEPTION;
User Defined Exception

Example
DECLARE
EX1 EXCEPTION;
N NUMBER(3);
BEGIN
N:=&NUM;
IF N > 10 THEN
RAISE EX1;
ELSE
DBMS_OUTPUT.PUT_LINE(‘No Exception’);
END_IF;
EXCEPTION
WHEN EX1 THEN
DBMS_OUTPUT.PUT_LINE(‘Exception Raised’);
END;
PRAGMA EXCEPTION_INIT

Some uncommon predefined errors numbers exists that


does have names

Oracle allows to associate a user-defined name with a


predefined error number( Oracle Error)

A pragma called EXCEPTION_INIT instructs the compiler to


associate or initialize a programmer-defined exception
with a specific Oracle error number
PRAGMA EXCEPTION_INIT

It is associated with a predefined number in the


declarative part

Syntax
PRAGMA EXCEPTION_INIT( EXCEPTION, ERROR_NUMBER);

Example
DECLARE
MYEXP EXCEPTION;
PRAGMA EXCEPTION_INIT(MYEXP, -1422);
RAISE_APPLICATION_ERROR

The RAISE_APPLICATION_ERROR procedure to communicate


application-specific errors from the server side (usually a
database trigger) to the client-side application

This built-in procedure is the only mechanism available for


communicating a server-side, programmer-defined exception
to the client side in such a way that the client process can
handle the exception

Error number should be of the range between –20000 and –


20999
RAISE_APPLICATION_ERROR

Error messages should be less than 512 characters

Syntax
RAISE_APPLICATION_ERROR( error_number in NUMBER,
error_msg in VARCHAR2);

Example
IF age < 18 THEN
RAISE_APPLICATION_ERROR (-20001, ‘Must be
eighteen years of age.');
END IF;
Cursors and Exceptions : Summary

A SQL cursor is a private Oracle SQL working area.

The implicit cursor is used by Oracle server to test and parse the SQL
statements

Implicit Cursors gives less programmatic control

An Implicit cursor is used for all other SQL statements

Explicit cursors are declared by the programmers

In explicit cursor the cursor name is explicitly attached to a select statement


Cursors and Exceptions : Summary

Explicit cursor handling requires Declaring, Opening, Fetching and Closing


cursor

Oracle raises ERRORS whenever any abnormal situation arises in a PL/SQL


block and performs an illegal termination of the execution of the program

PL/SQL traps and responds to errors using an architecture of EXCEPTION


handler

Pre-defined exceptions are already defined in the STANDARD package

Exceptions can be pre-defined(built-in) and user-defined


: Quiz

Create a cursor to print empno, ename, job, sal,


hiredate and the increment amount for all
employees. Increment amount depends on the
day of joining
Day of Joining Increment in %
Friday 20
Wednesday 18
Thursday 17
For all others 15
4.0 Procedures, Functions and Packages : Overview

Introduction:
PL/SQL procedures and functions are compiled database objects. Functions returns a scalar value and
PL/SQL procedures return nothing. Both can take zero or more number of parameters as input or output. A
package is a database object that groups logically related PL/SQL types, objects, and subprograms

Objective:
After completing this module, you will be able to,

1 . Understand Procedures
2. Creating Parameters
3. Passing Parameters
4. Creating Functions
5. Implement Packages
Procedures

Features

It is a sub program in the PL/SQL block, which can perform


a specific task when invoked explicitly with or without
parameter

IT has two parts, Specification and Body


 Specification: This section begins with the keyword Procedure
followed by its name and Parameter list(optional)
 Body: Procedure Body begins with the keyword IS/AS and ends
with the keyword END followed by the procedure name(optional)
Creating Procedures

Syntax
CREATE OR REPLACE PROCEDURE <PROCEDURE_NAME>
(<PARAMETER> [MODE] <DATA TYPE>,)
IS/AS
[LOCAL VARIABLE DECLARATION]
BEGIN
PL/SQL EXECUTABLE STATEMENT
[EXCEPTION]
[EXCEPTION HANDLERS]
END [PROGRAM UNIT NAME];
Creating Procedures

Example
CREATE OR REPLACE PROCEDURE AddStudent (
i_first_name student.first_name%type;
i_last_name student.last_name%type;
i_major student.major%type) AS
BEGIN
INSERT INTO student (id,first_name,last_name,major,credits)
values (student_sequence.nextval,i_first_name,i_last_name
,i_major,0);
commit;
END AddStudent;
Passing Parameters

Formal parameters can have three modes - IN, OUT or IN OUT

IN
 Default mode
 Takes the value inside the program
 Cannot be changed inside the sub- program
OUT
 Takes the value out of the sub- program
 Can be changed inside
INOUT
 Takes the value inside a sub- program and brings it out of the sub-
program
Passing Parameters

Procedure without parameter


CREATE OR REPLACE PROCEDURE procedure_name AS
/* Declarative section is here */
BEGIN
/* Executable section is here */
Exception
/* Exception section is here */
END [procedure_name]
Passing Parameters

Example of Procedure with Parameter


CREATE OR REPLACE PROCEDURE CALC_BONUS (
EMP_ID IN INTEGER,
BONUS OUT NUMBER) IS
MJOB EMP.JOB%TYPE;
BEGIN
SELECT SAL*0.10 INTO BONUS FROM EMP WHERE EMPNO =
EMP_ID;
IF MJOB = ‘MANAGER’ THEN
BONUS := 0;
END IF;
END CALC_BONUS;
Passing Parameters

Executing The Procedure


DECLARE
BON NUMBER;
ECODE NUMBER;
BEGIN
ECODE := &EMPLOYEE_NO;
CALC_BONUS(ECODE, BON);
DBMS_OUTPUT.PUT_LINE(‘The Bonus for the employee’ ||
ECODE || ‘ is’ || BON);

END;
/
Passing Parameters

Example of Procedure with INOUT Parameter


CREATE OR REPLACE PROCEDURE
FORMAT_PHONE_NO ( V_PHONE IN OUT
VARCHAR2)
IS
BEGIN
V_PHONE := ‘(‘ || SUBSTR(V_PHONE,1,3) ||
‘)’ || SUBSTR (V_PHONE,4,3) || ‘-’ ||
SUBSTR(V_PHONE,7);
END FORMAT_PHONE_NO;
/
Creating Functions

A function is a sub-program that is used to calculate value

Must RETURN a single value at a time

Can be used in a SELECT statement

Syntax
CREATE OR REPLACE FUNCTION< FUNCTION NAME>
[ARGUMENT]
RETURN DATATYPE IS[<LOCAL DECLARATION>]
BEGIN
EXECUTABLE STATEMENTS
[EXCEPTION] [EXCEPTION HANDLERS]
END [FUNCTION_NAME];
Creating Functions

Example
FUNCTION student_type (stud_code IN VARCHAR2)
RETURN VARCHAR2
IS
BEGIN
IF stud_code = ‘T' THEN
RETURN ‘Temp';
ELSIF stud_code = 'P' THEN
RETURN 'Parmanent';
END IF;
END;
Packages

A collection of Functions, Procedures, Global variables and


cursors stored in server in compiled form
Consists of 2 parts
 Package Specification : This acts as an interface to the user
applications. This part declares the , PL/SQL types, variables,
constants, exception, cursor & sub-programs(Functions and
procedures). This part is created using CREATE PACKAGE
command

 Package Body : It implements the specifications by defining the


cursors and sub-programs. This part is created using CREATE
PACKAGE BODY command
Packages

Oracle stores package specification and body


separately in the data dictionary
A package specification can exists without a
package body but not vice versa
Packages

An element of a package, whether it is a variable or a module, can


either be
Public
 When defined in the specification
 A public element can be referenced from other programs and PL/SQL
blocks
Private
 When defined only in the body of the package, but does not appear in
the specification
 A private element cannot be referenced outside of the package
 It can only be referenced by other elements within the package
Packages

The sub-programs that are present inside a package


cannot exist separately as database objects

A package cannot be called by itself. Only the procedures


and functions from within the package can be called with
reference to the package using the dot(.) operator

When one sub-program is called, then all other sub-


programs are also loaded into the memory, hence the
subsequent call for any other modules becomes fast
Packages

Example
CREATE PACKAGE PK1 CREATE PACKAGE BODY PK1 AS
AS I Integer :=0;
PROCEDURE P1; PROCEDURE P1 AS
BEGIN
PROCEDURE P2;
I := I + 100;
END PK1;
dbms_output.put_line(I);
END P1;
PROCEDURE P2 AS
BEGIN
I := I - 50;
dbms_output.put_line(I);
END P2;
END PK1;
Procedures, Functions and Packages : Summary

PL/SQL procedures/functions are compiled program


database objects, which can perform a specific task when
invoked explicitly with or without parameter

PL/SQL functions returns scalar values while procedures


nothing

PL/SQL procedure/function argument can be of input


(indicating the argument is read-only), output (indicating the
argument is write-only) or both (both readable and writable)
Procedures, Functions and Packages : Summary

A package is a compiled database objects logically


groups PL/SQL types, sub-programs etc. It consists
of two parts : specification and body

The specification is the interface to your


applications; it declares the types, variables,
constants, exceptions, cursors, and subprograms
available for use. The body fully defines cursors and
subprograms, and so implements the specification
: Quiz

Create a procedure which will accept a percentage and JOB,


and will show the reflection on the total salary. Calculate the
total salary before the increment for the particular JOB and
show the difference.

Create a procedure which will accept the LOAN amount and


EMPNO as input and display the installment amount and
number of installments to be paid. (Max loan amount will be
his current salary * total number of years of service. Loan will
be paid in equal monthly installment. Installment amount will
be 1/10th of monthly salary)
5.0 Triggers : Overview

Introduction:
A database trigger is a stored program unit associated with a database table. Triggers are used to
overcome the limitations of constraints and to supplement the declarative referential integrity while
implementing complex business rules or to audit changes to data

Objective:
After completing this module, you will be able to,

1 . Appreciate Database Triggers


2. Components of Triggers
3. Types of Triggers
4. Create Triggers
5. Order of Trigger Firing
Database Triggers

These are stored procedures that gets implicitly executed when some
database-related event occurs

Can be applied on any Table/View

Can be applied before the instruction is executed as well as after the


execution

Can work for any DML statements like INSERT, UPDATE and DELETE but
not for SELECT

Can be used to overcome the limitation of CHECK constraints


Database Triggers

Triggers should be designed to


 To perform operations that are related specific operations
 To perform operations that are global in nature

Triggers Should not be designed


 To replace the functionality that already exists in the Oracle Server

Syntax
CREATE OR REPLACE TRIGGER <TRIGGER_NAME>
[BEFORE/AFTER] [INSERT/UPDATE/DELETE]
ON <TABLE_NAME>
[ FOR EACH ROW [WHEN triggering_condition]]
trigger_body;
Components of Triggers

Trigger Timing
 IT means when a trigger should fire. The possible trigger timing are BEFORE,
AFTER

Trigger Event
 The trigger event can be INSERT, UPDATE or DELETE

Trigger Type
 The type of trigger can be Statement or Row

Trigger Body
 This section specifies the action need to be performed by the trigger i.e. it is
the PL/SQL block that gets executed
Types of Triggers

Row Level
 The action specified with the row level trigger will be executed for each
affected row by the instruction for which the trigger is invoked
 These triggers will fire for every INSERT/UPDATE/DELETE on the table
depending on the number of rows affected by by the triggering event
 Should specify the keyword FOR EACH ROW

Statement Level
 They get fired in the table level once for each trigger event
 These triggers will fire for every INSERT/UPDATE/DELETE on the table
irrespective of the number of rows affected by by the triggering event
 To define a statement level trigger omit the FOR EACH ROW keyword in
the trigger specification
Creating Triggers

Example of Statement Level Trigger


CREATE OR REPLACE TRIGGER major_stats
BEFORE INSERT ON major_stats
BEGIN
INSERT INTO temp_table (char_col)
VALUES (‘Trigger fired’);
END major_stats;
/
Creating Triggers

Row Level Trigger


Row level trigger use :old and :new qualifiers to access value of a column
before or after the change of data caused by a DML operation
Old and New qualifiers can only be used in Row level triggers
The table illustrates the old and new value of a database table column before
and after DML operation

DML Operations Value Before Change Value After Change

INSERT NULL Value that is inserted


UPDATE Value before update Value before update
DELETE Value before update NULL
Creating Triggers

Example of Row Level Trigger


CREATE OR REPLACE TRIGGER TempDelete
BEFORE DELETE ON temp_table
FOR EACH ROW
DECLARE
v_TempRec temp_table%ROWTYPE;
BEGIN
v_TempRec.char_col := :old.char_col;
v_TempRec.num_col := old.num_col;
END TempDelete;
Order of Trigger Firing

Execute the BEFORE statement level trigger, if present

For each row affected by the statement,


 Execute the BEFORE row-level trigger, if present.
 Execute the statement itself.
 Execute the AFTER row-level trigger, if present.

Execute the after statement-level trigger, if present


Triggers : Summary

Triggers are stored procedures that gets implicitly executed when some
database-related event occurs

Can work for any DML statements like INSERT, UPDATE and DELETE but not for
SELECT

Triggers can be row level and statement level.

The action specified with the row level trigger will be executed for each
affected row by the instruction for which the trigger is invoked

The statement level triggers will fire for every INSERT/UPDATE/DELETE on the
table irrespective of the number of rows affected by by the triggering event
: Quiz

Write a trigger on the EMP table, so that after


each insertion of new record, or updation of old
one, the NOE column of the dept table gets
updated. Add a column NOE to the dept table,
which will record the number of rows for each
department. In case of record updation the NOE
of one department should be reduced and
another should be incremented.
6.0 PL/SQL Collections : Overview

Introduction:
Oracle implements collection using Tables and Varrays

Objective:
After completing this module, you will be able to,

1. Understand Collections
2. Types of Collection
3. Define and Declare Collection
4. Use Collection Methods
5. Learn Multi-level collection
Collection

A collection is a ordered group of elements, all of the same type

It is a general concept that encompasses list, arrays and other


familiar datatypes

Each element has a unique subscript that determines its


position in the collection

Collections work like the arrays found in most third-generation


programming language
Types of Collection

PL/SQL has two collection types:

Tables

Varrays

Tables comes in two flavors


 Index by tables(formerly called PL/SQL tables)
 Nested Tables
Types of Collection

Index-by Tables
Also known as associative arrays, lets you look up
elements using arbitrary numbers and strings for
subscript values.

They are similar to one-dimensional arrays and are


referenced like arrays of records. Since Index-By tables
can be passed as parameters, they can be used to move
columns of data into and out of database tables or
between client-side applications and stored subprograms
Types of Collection

Nested Tables
Nested tables hold an arbitrary number of elements.

They use sequential numbers as subscripts.

Within the database, nested tables can be considered one-column


database tables

Oracle stores the rows of a nested table in no particular order.

when the nested table is retrieve into a PL/SQL variable, the rows are
given consecutive subscripts starting at 1. That gives array-like access to
individual rows.
Types of Collections

Difference between Array and Nested Tables


First, arrays have a fixed upper bound, but nested
tables are unbounded. So, the size of a nested table
can increase dynamically

Second, arrays must be dense (have consecutive


subscripts). So, individual elements cannot be deleted
from an array. Initially, nested tables are dense, but
they can be sparse (have nonconsecutive subscripts).
Types of Collections

Elements from a nested table can be deleted


using the built-in procedure DELETE. That might
leave gaps in the index, but the built-in function
NEXT allows iteration over any series of
subscripts
Types of Collections

Varrays
Items of type VARRAY are called varrays
Allow to associate a single identifier with an entire
collection
Manipulate the collection as a whole and reference
individual elements easily
To reference an element, use standard subscripting
syntax
Example,
Grade (3) references the third element in varray Grades.
Declaring and Defining Collection

Define a collection type and declare variables of that type

Syntax for Index-by tables:


TYPE type_name IS TABLE OF element_type [NOT NULL]
INDEX BY [BINARY_INTEGER | PLS_INTEGER |
VARCHAR2(size_limit)];

INDEX BY key_type;
 Type_name is a type specifier used later to declare collections.
 Element_type is any PL/SQL datatype.
 Key_type can be numeric, either BINARY_INTEGER or PLS_INTEGER.
 It can also be VARCHAR2 or one of its subtypes VARCHAR, STRING, or LONG.
You mustSpecify the size. (Varchar2 (1000);)
Declaring and Defining Collection

Syntax for Nested tables:


TYPE type_name IS TABLE OF element_type [NOT NULL];
 type_name is a type specifier used later to declare collections
 element_type is any PL/SQL datatype.

Syntax for Varrays:


TYPE type_name IS {VARRAY | VARYING ARRAY} (size_limit)
OF element_type [NOT NULL];
 type_name and element_type are the same as for nested tables.size_limit is a
positive integer literal representing the maximum number of elements in the array
When defining a VARRAY type, must specify its maximum size.
Example, of a type that stores up to 366 dates:
DECLARETYPE Calendar IS VARRAY (366) OF DATE;
Declaring and Defining Collection

Example of Index- by Tables


 DECLARE
TYPE EmpTabTyp IS TABLE OF emp%ROWTYPE /* Create
a type */ INDEX BY BINARY_INTEGER;
emp_tab EmpTabTyp; /* Declaration of variable of
collection type */
 TYPE typ_number IS TABLE OF NUMBER INDEX BY
BINARY_INTEGER;
empid_tab typ_number; /* Declaration of
variable of collection type */
BEGIN /* Retrieve employee record. */
SELECT * INTO emp_tab(7468) FROM emp WHERE empno =
7468;
Declaring and Defining Collection

SELECT EMPID
BULK COLLECT INTO empid_tab
FROM EMP;
IF empid_tab.last > 0 THEN
FORALL I in 1.. empid_tab.last
LOOP
Dbms_output.put_line(‘Empid: ‘||
empid_tab(i)) END LOOP
END IF;
END;
Declaring and Defining Collection

Example of Nested Tables:


CREATE TYPE CourseList AS TABLE OF VARCHAR2(10)
-- define type
/
CREATE TYPE Student AS OBJECT ( -- create object
id_num INTEGER(4),
name VARCHAR2(25),
address VARCHAR2(35),
status CHAR(2),
courses CourseList) -- declare nested table as
attribute
/
Declaring and Defining Collection

Example of Nested Tables:


CREATE OR REPLACE TYPE TYP_NUMBER AS TABLE OF
NUMBER
/
CREATE TABLE TMP
(EMPID NUMBER,
EMPNAME VARCHAR2 (100),
PHONENUMBER TYP_NUMBER
)
NESTED TABLE PHONENUMBER STORE AS
PHONENUMBER_TAB
/
Declaring and Defining Collection

Example of Varrays
CREATE TYPE ProjectList AS VARRAY(50) OF
VARCHAR2(16);
/
CREATE TABLE department ( -- create database
table
dept_id NUMBER(2),
name VARCHAR2(15),
budget NUMBER(11,2),
-- Each department can have up to 50 projects.
projects ProjectList)
/
Using Collection Methods

A collection method is a built-in function or procedure that


operates on collection

Is called using dot notation

Syntax:
 collection_name.method_name[(parameters)]

The following collection methods help generalize code, make


collections easier to use,And make your application easier to
maintain
Using Collection Methods

EXISTS(n) - Returns TRUE if the specified element exists.

COUNT - Returns the number of elements in the


collection.

LIMIT - Returns the maximum number of elements for a


VARRAY, or NULL for nested tables. This is specifically
useful to determine batch size when dealing with large
number of records, so that the records can be sized to fit
into free memory for faster processing.
Using Collection Methods

FIRST - Returns the index of the first element in the collection.

LAST - Returns the index of the last element in the collection.

PRIOR(n) - Returns the index of the element prior to the specified element

NEXT(n) - Returns the index of the next element after the specified
element.

EXTEND - Appends a single null element to the collection.

EXTEND(n) - Appends n null elements to the collection.


Using Collection Methods

EXTEND(n1, n2) - Appends n1 copies of the n2th element to


the collection
TRIM - Removes a single element from the end of the
collection.
TRIM(n) - Removes n elements from the end of the collection.
DELETE - Removes all elements from the collection.
DELETE(n) - Removes element n from the collection.
DELETE(n1,n2) - Removes all elements from n1 to n2 from the
collection
Multi-level Collection

It’s a collection within collections

Examples are Nested table of varrays, Varrays of varrays etc

Multilevel VARRAY Example


declare
type t1 is varray(10) of integer;
type nt1 is varray(10) of t1; -- multilevel
va t1 := t1(2,3,5);
-- initialize multilevel varray
nva nt1 := nt1(va, t1(55,6,73), t1(2,4),
i integer;
va1 t1;
begin
-- multilevel access
i := nva(2)(3); -- i will get value 73
dbms_output.put_line(i);
PL/SQL Collection : Summary

A collection is a ordered group of elements, all of the same


type

Each element has a unique subscript that determines its


position in the collection

PL/SQL has two collection types: Tables, Varrays

Tables comes in two flavors Index by tables (formerly called


PL/SQL tables) and Nested Tables
: Quiz

Study the following code,


CREATE TYPE CourseList AS TABLE OF VARCHAR2(10) --
define type
/
CREATE TYPE Student AS OBJECT ( -- create object
id_num INTEGER(4),
name VARCHAR2(25),
address VARCHAR2(35),
status CHAR(2),
courses CourseList) -- declare nested table as attribute
/
If courses . DELETE(2); deletes element 2 and courses . DELETE(7,7) delete
element 7Then courses. DELETE(6,3) delete which element?
Bulk Operations

PL/SQL is very tightly integrated with the Oracle


database SQL engine, but this tight integration does
not mean that there isn’t any overhead associated
with executing SQL statements from PL/SQL

When a PL/SQL program executes, the procedural


portions are executed by the PL/SQL engine, but all
SQL statement are passed to SQL layer for execution,
then data is passed back to the procedural engine
Bulk Operations

The transfer of data back and forth from PL/SQL


to SQL and back again is called context switching.
The more switches occur the more performance
degrades. Two new enhancements

BULK COLLECT and the FORALL statements allows


to bulk together all of the context switches into a
single switch and pass that to the SQL engine
FOR ALL

A variation on the classic FOR LOOP that bundles together


multiple DML statements based on a collection

Bulk DML using the FORALL statement will also take advantage of
turning multiple context switches into a single context switch.

The FORALL statement must follow these simple rules:

The body of the FORALL statement must contain a single DML


operation.
FOR ALL

The DML must reference collection elements, indexed by the


index_row variable in the FORALL statement. The scope of the
index_row variable is the FORALL statement only; you may not
reference it outside of that statement

Do not declare an INTEGER variable for index_row. It is


declared implicitly by the PL/SQL engine

The lower and upper bounds must specify a valid range of


consecutive index numbers for the collection(s) referenced in
the SQL statement.
FOR ALL

Example
PROCEDURE proc_bulk_collect IS
CURSOR cur_emp IS
SELECT emono
FROM emp;
TYPE tt_empno IS TABLE OF emp.empno%TYPE INDEX BY BINARY_INTEGER;
tab_emono tt_empno;
BEGIN
OPEN cur_emp;
FETCH cur_emp INTO BULK COLLECT tab_emono;
close cur_emp;
FORALL i IN tab_emono.FIRST..tab_emono.LAST LOOP
DELETE FROM new_emp
WHERE empno = tab_emono(i);
END LOOP;
end;
BULK COLLECT

An enhancement to explicit and implicit cursor query


operation that allows the transfer of multiple rows of
data in one trip to the SQL engine
PROCEDURE proc_bulk_collect IS
CURSOR cur_emp IS
SELECT emono,ename
FROM emp;
TYPE tt_empno IS TABLE OF emp.empno%TYPE INDEX BY BINARY_INTEGER;
tab_emono tt_empno;
TYPE tt_ename IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER;
tab_ename tt_ename;
BEGIN
OPEN cur_emp;
FETCH cur_emp INTO BULK COLLECT tab_emono,tab_ename;
close cur_emp;
END;
Difference between soft parse and hard parse

Soft parse: Statement, which are parsed and already in


the shared pool, those statements for re-execution need
not require parsing if it is found in the shared Pool. A
shorter process to getting the query result

Hard parse: statement, which are parsed every time


during the execution is called Hard parse. If we have to
Hard Parse a large percentage of our queries, our system
will function slowly and in some cases. Hard parse can
be avoid by using bind variable in subprogram
: Quiz

 The following are the two Dynamic SQL statements. What is the main difference
between this two statements in the respect of execution.
Begin
EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)';
End;
/
CREATE OR REPLACE PROCEDURE CREATE_TABLE2 AS
cur integer;
rc integer;
BEGIN cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)',
DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
/
Oracle - Summary

An Oracle server consists of an Oracle database and an Oracle server


instance

Oracle processes can be user process and server process

Physical database structure includes data file, redo log file and control
files

All the data dictionary tables and views for a given database are stored
in that database’s SYSTEM tablespace

SQL is an English-like, non-procedural language


Oracle - Summary

SQL is used in creating, modifying and deleting database objects

SQL *PLUS is an Oracle tool. It recognizes and submits SQL


statements residing in the SQL buffer (memory area) for
execution to the Oracle server

PL/SQL extends SQL by adding constructs found in other


procedural languages like conditional constructs, looping,
variables data types, procedures, functions etc.

A SQL cursor is a private Oracle SQL working area


Oracle - Summary

The implicit cursor is used by Oracle server to test and parse


the SQL statements. Explicit cursors are declared by the
programmers

PL/SQL traps and responds to errors using an architecture of


EXCEPTION handler. Pre-defined exceptions are already
defined in the STANDARD package

PL/SQL procedures/functions are compiled program database


objects, which can perform a specific task when invoked
explicitly with or without parameter
Oracle - Summary

A package is a compiled database objects logically groups PL/SQL


types, sub-programs etc. It consists of two parts : specification
and body

Triggers are stored procedures that gets implicitly executed when


some database-related event occurs

A collection is a ordered group of elements, all of the same type

Dynamic SQL enables to write programs that reference SQL


statements whose full text is not known until runtime
Congratulations!
You have successfully
completed

Oracle 9i

You might also like