Sei sulla pagina 1di 93

Unit 4:Understand PL / SQL

By,
Asmatullah Khan,
CL/CP, GIOE,
Secunderabad.
Outline
PL/SQL
• PL/SQL stands for Procedural Language extensions
to the Structured Query Language (SQL).

• Oracle created PL/SQL that extends some


limitations of SQL to provide a more
comprehensive solution for building mission-
critical applications running on Oracle database.

• PL/SQL is a procedural extension of SQL, making it


extremely simple to write procedural code that
includes SQL as if it were a single language.
What is so great about PL/SQL anyway?
• In comparison, most other programming languages require
mapping data types, preparing statements and processing result
sets, all of which require knowledge of specific APIs.

• The data types in PL/SQL are a super-set of those in the database,


so you rarely need to perform data type conversions when using
PL/SQL.

• When coding business logic in middle tier applications, a single


business transaction may be made up of multiple interactions
between the application server and the database adding a
significant overhead associated with network traffic.

• In comparison, building all the business logic as PL/SQL in the


database means client code needs only a single database call per
transaction, reducing the network overhead significantly.
SQL vs PL/SQL database network traffic
PL/SQL Architecture
• The PL/SQL architecture mainly consists of following 3 components:
1. PL/SQL block
2. PL/SQL Engine
3. Database Server
PL/SQL Architecture - Blocks
• Is the component which has the actual PL/SQL code.

• Consists of different sections to divide the code logically (declarative section


for declaring purpose, execution section for processing statements,
exception handling section for handling errors). It also contains the SQL
instruction that can be used to interact with the database server.

• All the PL/SQL units are treated as PL/SQL blocks, and this is the starting
stage of the architecture which serves as the primary input.

• Following are the different type of PL/SQL units.


1. Anonymous Block
2. Function
3. Library
4. Procedure
5. Package Body
6. Package Specification
7. Trigger
8. Type
9. Type Body
PL/SQL Architecture - Engine
• PL/SQL engine is the
component where the
actual processing of the
codes takes place.

• It separates PL/SQL
units and SQL part in the
input.

▫ The separated PL/SQL


units will be handled with
the PL/SQL engine itself.

▫ The SQL part will be sent


to database server where
the actual interaction
with database takes place.
Database Server
• This is the most
important component of
Pl/SQL unit which stores
the data.

• The PL/SQL engine uses


the SQL from PL/SQL
units to interact with the
database server.

• It consists of SQL
executor which actually
parses the input SQL
statements and execute
the same.
PL/SQL Features
• PL/SQL is tightly integrated with SQL.

• Offers extensive error checking.

• Provides numerous data types.

• Contains a variety of programming structures.

• Supports structured programming through functions and


procedures.

• Supports object-oriented programming.

• Useful for developing web applications and server pages.


Facts about PL/SQL
• PL/SQL is a completely portable, high-performance transaction-
processing language.

• PL/SQL provides a built-in interpreted and OS independent


programming environment.

• PL/SQL can also directly be called from the command-line SQL*Plus


interface.

• Direct call can also be made from external programming language


calls to database.

• PL/SQL's general syntax is based on that of ADA and Pascal


programming language.

• Apart from Oracle, PL/SQL is available in TimesTen in-memory


database and IBM DB2.
Advantages of PL/SQL
• SQL is the standard database language and PL/SQL is strongly integrated with SQL.

• PL/SQL supports both static and dynamic SQL.


▫ Static SQL supports DML operations and transaction control from PL/SQL block.
▫ Dynamic SQL is SQL allows embedding DDL statements in PL/SQL blocks.

• PL/SQL allows sending an entire block of statements to the database at one time. This reduces
network traffic and provides high performance for the applications.

• PL/SQL gives high productivity to programmers as it can query, transform, and update data in a
database.

• PL/SQL saves time on design and debugging by strong features, such as exception handling,
encapsulation, data hiding, and object-oriented data types.

• Applications written in PL/SQL are fully portable.

• PL/SQL provides high security level.

• PL/SQL provides access to predefined SQL packages.


SQL vs PL/SQL

SQL PL/SQL
PL/SQL is a block of codes that used to
SQL is a single query that is used to
write the entire program blocks/
perform DML and DDL operations.
procedure/ function, etc.

It is declarative, that defines what needs


PL/SQL is procedural that defines how
to be done, rather than how things need
the things needs to be done.
to be done.
Execute as a single statement. Execute as a whole block.
Mainly used to manipulate data. Mainly used to create an application.

Interaction with Database server. No interaction with the database server.

It is an extension of SQL, so it can


Cannot contain PL/SQL code in it.
contain SQL inside it.
Syntax of
PL/SQL Block
Structure
PL/SQL Data Type
Category Description
Single values with no internal components,
Scalar
such as a NUMBER, DATE, or BOOLEAN.
Pointers to large objects that are stored
Large Object separately from other data items, such as
(LOB) text, graphic images, video clips, and
sound waveforms.
Data items that have internal components
Composite that can be accessed individually. For
example, collections and records.
Reference Pointers to other data items.
PL/SQL Scalar Data Types and
Subtypes
Date
Description
Type
Numeric values on which arithmetic
Numeric
operations are performed.
Alphanumeric values that represent
Character single characters or strings of
characters.
Logical values on which logical
Boolean
operations are performed.
Datetime Dates and times.
Numeric Data Types and Subtypes
Data Type Description
PLS_INTEGER Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits
BINARYINTEGER Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits
BINARY_FLOAT Single-precision IEEE 754-format floating-point number
BINARY_DOUBLE Double-precision IEEE 754-format floating-point number
Fixed-point or floating-point number with absolute value in range 1E-130 to (but not
NUMBER(prec, scale)
including) 1.0E126.
DEC(prec, scale) ANSI specific fixed-point type with maximum precision of 38 decimal digits.
DECIMAL(prec, scale) IBM specific fixed-point type with maximum precision of 38 decimal digits.
NUMERIC(pre, secale) Floating type with maximum precision of 38 decimal digits.
ANSI specific floating-point type with maximum precision of 126 binary digits
DOUBLE PRECISION
(approximately 38 decimal digits)
ANSI and IBM specific floating-point type with maximum precision of 126 binary
FLOAT
digits (approximately 38 decimal digits)
INT ANSI specific integer type with maximum precision of 38 decimal digits
INTEGER ANSI and IBM specific integer type with maximum precision of 38 decimal digits
SMALLINT ANSI and IBM specific integer type with maximum precision of 38 decimal digits
Floating-point type with maximum precision of 63 binary digits (approximately 18
REAL
decimal digits)
PL/SQL Character Data Types and
Subtypes
Data Type Description
CHAR Fixed-length character string with maximum size of 32,767 bytes
VARCHAR2 Variable-length character string with maximum size of 32,767 bytes
Variable-length binary or byte string with maximum size of 32,767
RAW
bytes, not interpreted by PL/SQL
Fixed-length national character string with maximum size of 32,767
NCHAR
bytes
Variable-length national character string with maximum size of 32,767
NVARCHAR2
bytes
LONG Variable-length character string with maximum size of 32,760 bytes
Variable-length binary or byte string with maximum size of 32,760
LONG RAW
bytes, not interpreted by PL/SQL
ROWID Physical row identifier, the address of a row in an ordinary table
UROWID Universal row identifier (physical, logical, or foreign row identifier)
PL/SQL Boolean Data Types
• The BOOLEAN data type stores logical values that
are used in logical operations. The logical values are
the Boolean values TRUE and FALSE and the value
NULL.

• However, SQL has no data type equivalent to


BOOLEAN.

• Therefore, Boolean values cannot be used in:


▫ SQL statements
▫ Built-in SQL functions (such as TO_CHAR)
▫ PL/SQL functions invoked from SQL statements
PL/SQL Datetime and Interval Types
Field Name Valid Datetime Values Valid Interval Values

YEAR -4712 to 9999 (excluding year 0) Any nonzero integer


MONTH 01 to 12 0 to 11
01 to 31 (limited by the values of
DAY MONTH and YEAR, according to the Any nonzero integer
rules of the calendar for the locale)
HOUR 00 to 23 0 to 23
MINUTE 00 to 59 0 to 59
0 to 59.9(n), where 9(n) is the
00 to 59.9(n), where 9(n) is the
SECOND precision of interval fractional
precision of time fractional seconds
seconds
-12 to 14 (range accommodates
TIMEZONE_HOUR Not applicable
daylight savings time changes)
TIMEZONE_MINUTE 00 to 59 Not applicable
Found in the dynamic performance
TIMEZONE_REGION Not applicable
view V$TIMEZONE_NAMES
Found in the dynamic performance
TIMEZONE_ABBR Not applicable
view V$TIMEZONE_NAMES
PL/SQL Large Object (LOB) Data Types
• Large object (LOB) data types refer large to data items such as
text, graphic images, video clips, and sound waveforms. LOB data
types allow efficient, random, piecewise access to this data.

Data Type Description Size


Used to store large binary objects in System-dependent.
BFILE operating system files outside the Cannot exceed 4
database. gigabytes (GB).
Used to store large binary objects in the 8 to 128 terabytes
BLOB
database. (TB)
Used to store large blocks of character
CLOB 8 to 128 TB
data in the database.
Used to store large blocks of NCHAR
NCLOB 8 to 128 TB
data in the database.
PL/SQL User-Defined Subtypes
• A subtype is a subset of another data type, which is called its
base type. A subtype has the same valid operations as its
base type, but only a subset of its valid values.
NULLs in PL/SQL
• PL/SQL NULL values represent missing or unknown
data and they are not an integer, a character, or any
other specific data type.

• NULL is not the same as an empty data string or the


null character value '\0'.

• A null can be assigned but it cannot be equated with


anything, including itself.
The %TYPE Attribute
• %TYPE attribute is used to declare a variable
according to:
▫ A database column definition
▫ Another previously declared variable
PL/SQL Block Types - recap
Anonymous Procedure Function
Other types of PL/SQL Program Constructs
Anonymous block
• PL/SQL program units organize
the code into blocks. A block
without a name is known as an [DECLARE]
anonymous block.    Declaration statements;
BEGIN
   Execution statements;
• It is called anonymous block   [EXCEPTION]
because it is not saved in the       Exception handling statements;
Oracle database. END;
/

• An anonymous block is an only


one-time use code.

• Useful in certain situations such


as creating test units.
Anonymous block has three basic sections
• The anonymous block has three basic sections that are the
declaration, execution, and exception handling.

• Only the execution section is mandatory and all others are optional.

▫ The declaration section allows you to define data types, structures, and
variables.
 You often declare variables in the declaration section by giving them names, data
types, and initial values.

▫ The execution section is required in a block structure and it must have at least
one statement.
 The execution section is the place where you put the execution code or business
logic code.
 You can use both procedural and SQL statements inside the execution section.

▫ The exception handling section is starting with the EXCEPTION keyword.


 The exception section is the place that you put the code to handle exceptions.
Variable Declaration in PL/SQL
• PL/SQL variables must be declared in the declaration
section or in a package as a global variable.
Rules for Variable Declarations and Initialization
• Initialize variables designated as NOT NULL and
CONSTANT.
• Initialize identifiers by using the assignment
operator (:=) or the DEFAULT reserved word.
• Declare at most one identifier per line.
• Two variables can have the same name, provided
they are in different blocks.
• The variable name (identifier) should not be the
same as the name of table columns used in the
block.
Circle
Demo
Variable Scope in PL/SQL
• PL/SQL allows the nesting of Blocks, i.e., each program
block may contain another inner block.

• If a variable is declared within an inner block, it is not


accessible to the outer block. However, if a variable is
declared and accessible to an outer block, it is also
accessible to all nested inner Blocks.

• There are two types of variable scope:


▫ Local variables - variables declared in an inner block
and not accessible to outer blocks.
▫ Global variables - variables declared in the outermost
block or a package.
Assigning SQL Query Results to PL/SQL
Variables
Arithmetic Operators
Operator Description Example (A=10, B=5)
+ Adds two operands A + B will give 15
Subtracts second
- A - B will give 5
operand from the first
Multiplies both
* A * B will give 50
operands
Divides numerator by
/ A / B will give 2
de-numerator
Exponentiation
operator, raises one
** A ** B will give 100000
operand to the power
of other
Relational Operators
Operator Description Example (A=5, B=10)
Checks if the values of two operands are equal or not,
= (A = B) is not true.
if yes then condition becomes true.
!=
Checks if the values of two operands are equal or not,
<> (A != B) is true.
if values are not equal then condition becomes true.
~=
Checks if the value of left operand is greater than the
> value of right operand, if yes then condition becomes (A > B) is not true.
true.
Checks if the value of left operand is less than the
< value of right operand, if yes then condition becomes (A < B) is true.
true.
Checks if the value of left operand is greater than or
>= equal to the value of right operand, if yes then (A >= B) is not true.
condition becomes true.
Checks if the value of left operand is less than or
<= equal to the value of right operand, if yes then (A <= B) is true.
condition becomes true.
Comparison Operator
Operator Description Example
The LIKE operator compares a
If 'Zara Ali' like 'Z% A_i' returns a
character, string, or CLOB value
Boolean true, whereas, 'Nuha Ali'
LIKE to a pattern and returns TRUE if
like 'Z% A_i' returns a Boolean
the value matches the pattern
false.
and FALSE if it does not.
The BETWEEN operator tests If x = 10 then, x between 5 and 20
whether a value lies in a specified returns true, x between 5 and 10
BETWEEN
range. x BETWEEN a AND b returns true, but x between 11 and
means that x >= a and x <= b. 20 returns false.
The IN operator tests set
If x = 'm' then, x in ('a', 'b', 'c')
membership. x IN (set) means
IN returns boolean false but x in ('m',
that x is equal to any member of
'n', 'o') returns Boolean true.
set.
The IS NULL operator returns
the BOOLEAN value TRUE if its
operand is NULL or FALSE if it is If x = 'm', then 'x is null' returns
IS NULL
not NULL. Comparisons Boolean false.
involving NULL values always
yield NULL.
Built-in String Functions in PL/SQL
Function Description Example
Returns a portion of src starting at position p and l
substr(src, p, l) substr('Hello',3,2) = 'll'
char. long
upper Converts to uppercase upper('Hello') = 'HELLO'
lower Converts to lowercase lower('HELLO') = 'hello'
initcap('HELLO, world!') = 'Hello,
initcap Capitalizes the first character or each word
World!'
ltrim Removes blanks at the left-end of a string ltrim('   Hello   ') = 'Hello   '
rtrim Removes blanks at the right-end of a string rtrim('   Hello ') = '   Hello'
trim Removes blanks at either ends of a string trim('   Hello   ') = 'Hello'
concat Concatenates two strings concat('Hel', 'lo') = 'Hello'
length Returns the length of a string length('Hello') = 5
Replaces every occurrence of x in src by y (or by replace('Hello', 'll', 'r') = 'Hero'
replace(src, x, y)
nothing if y is absent) replace('Hello', 'o') = 'Hell'
lpad('Hello', 10, '>') =
lpad(src, l, p) Returns src, left-padded to length n with the string p
'>>>>>Hello'
rpad(src, l, p) Returns src, right-padded to length n with the string p rpad('Hello', 10, '!') = 'Hello!!!!!'
chr Returns a character's code chr('H') = 72
soundex Computes the soundex phonetic value of a string
Replaces each char. from x in src by the corresponding translate('hello', 'hl', 'HL') =
translate(str,x,y)
char. in y 'HeLLo'
nls_initcap Same as initcap with National Language Support (NLS)
nls_upper Same as upper with National Language Support (NLS) nls_upper('Café) = CAFÉ
nls_lower Same as lower with National Language Support (NLS)
Built-in Conversion Functions in PL/SQL
Function
Usage EXAMPLE
Function Name
Usage EXAMPLE
Name ADD_MONTHS Adds the given ADD_MONTH('2
015-01-01',5);
Converts (date, no.of months to the Output:
the other months) date 06/01/2015
TO_CHAR datatype to TO_CHAR(123);
character Returns the Select SYSDATE
datatype current date from dual;
SYSDATE Output: 10/4/2015
Converts and time of the
2:11:43 PM
the given server
string to
TO_DATE('2015-JAN-15', 'YYYY-
TO_DATE date. The Round of the select sysdate,
MM-DD'); TRUNC(sysdate)
(string, format) string
Output: 2015-01-15 date variable
should TRUNC from dual; Output:
to the lower 10/4/2015 2:12:39
match with
possible value PM 10/4/2015
the format.
Rounds the Select sysdate,
Converts date to the ROUND(sysdate)
the text to Select TO_NUMBER('1234','9999')
number from dual;
ROUND nearest limit from dual Output:
either higher 10/4/2015 2:14:34
type of the Output: 1234 PM 10/5/2015
TO_NUMBER given or lower
(text, format) format. Select
Returns the Select
Informat '9' TO_NUMBER('1234.453','9,999.99 MONTHS_BETW
denotes the ') from dual; number of
MONTHS_BE EEN (sysdate+60,
number of Output: 1,234.45 months sysdate) from dual
TWEEN
digits between two
dates Output: 2
Built-in Function Examples
DECLARE
l_company_name VARCHAR2 (25) := 'oraCLE corporatION';

BEGIN
DBMS_OUTPUT.put_line (UPPER (l_company_name));
DBMS_OUTPUT.put_line (LOWER (l_company_name));
DBMS_OUTPUT.put_line (INITCAP (l_company_name));
END;
/

OUTPUT:
ORACLE CORPORATION
oracle corporation
Oracle Corporation
DECLARE
l_company_name VARCHAR2 (6) := 'Oracle';
BEGIN
/* Retrieve the first character in the string */
DBMS_OUTPUT.put_line (SUBSTR (l_company_name, 1, 1));
/* Retrieve the last character in the string */
DBMS_OUTPUT.put_line (SUBSTR (l_company_name, -1, 1));
/* Retrieve three characters, starting from the second position. */
DBMS_OUTPUT.put_line (SUBSTR (l_company_name, 2, 3));
/* Retrieve the remainder of the string, starting from the second position. */
DBMS_OUTPUT.put_line (SUBSTR (l_company_name, 2));
END;
/

The output from this block is:


O
e
rac
racle
DECLARE
l_first VARCHAR2 (10) := 'Steven';
l_last VARCHAR2 (20) := 'Feuerstein'; The output from this block is:
Header
l_phone VARCHAR2 (20) := '773-426-9093'; ...Sub-header
BEGIN abc12312312312312312
First Name Last Name Phone
/* Indent the subheader by 3 characters */ Steven Feuerstein 773-426-9093

DBMS_OUTPUT.put_line ('Header');
DBMS_OUTPUT.put_line (LPAD ('Sub-header', 13, '.'));

/* Add "123" to the end of the string, until the 20 character is reached.*/
DBMS_OUTPUT.put_line (RPAD ('abc', 20, '123'));

/* Display headers and then values to fit within the columns. */


DBMS_OUTPUT.put_line (/*1234567890x12345678901234567890x*/
'First Name Last Name Phone');
DBMS_OUTPUT.put_line (RPAD (l_first, 10)|| ' '|| RPAD (l_last, 20)|| ' '||
l_phone);
END;
/
DECLARE
l_name VARCHAR2 (50) := 'Steven Feuerstein';
BEGIN
/* Replace all e's with the number 2. Since you are replacing a single
character, you can use either REPLACE or TRANSLATE. */
DBMS_OUTPUT.put_line (REPLACE (l_name, 'e', '2'));
DBMS_OUTPUT.put_line (TRANSLATE (l_name, 'e', '2'));

/* Replace all instances of "abc" with "123" */


DBMS_OUTPUT.put_line (REPLACE ('abc-a-b-c-abc', 'abc', '123'));
/* Replace "a" with "1", "b" with "2", "c" with "3". */
DBMS_OUTPUT.put_line (TRANSLATE ('abc-a-b-c-abc', 'abc','123'));
END;
/ The output from this block is:
St2v2n F2u2rst2in
St2v2n F2u2rst2in
123-a-b-c-123
123-1-2-3-123
DECLARE
x VARCHAR2 (30)
:= '.....Hi there!.....';
BEGIN
DBMS_OUTPUT.put_line (TRIM (LEADING '.' FROM x));
DBMS_OUTPUT.put_line (TRIM (TRAILING '.' FROM x));
DBMS_OUTPUT.put_line (TRIM (BOTH '.' FROM x));

--The default is to trim


--from both sides
DBMS_OUTPUT.put_line (TRIM ('.' FROM x));

--The default trim character


--is the space: The output from this block is:
DBMS_OUTPUT.put_line (TRIM (x)); Hi there!.....
END; .....Hi there!
/ Hi there!
Hi there!
.....Hi there!.....
PL/SQL Records
• A PL/SQL record is a data structure that can hold data items of
different kinds.

• Records consist of different fields, similar to a row of a database


table.

• PL/SQL can handle the following types of records:


▫ Table-based
▫ Cursor-based records
▫ User-defined records

 The %ROWTYPE attribute enables a programmer to create table-


based and cursor-based records.

 PL/SQL provides a user-defined record type that allows you to define


different record structures.
▫ Records consist of different fields.
Table-Based Records Example
Cursor Based Records Example
User Defined Record Example
Using
Procedure
PL/SQL tables
PL/SQL Record Structure

• PL/SQL has two composite datatypes:


▫ TABLE and
▫ RECORD.

• Objects of type TABLE are known as PL/SQL Advantages of PL/SQL Tables


tables.
•PL/SQL tables help you move bulk data.
• PL/SQL tables use a primary key to give you
array-like access to rows. The number of rows in
a PL/SQL table can increase dynamically. •They can store columns or rows of Oracle data,
and they can be passed as parameters.
• PL/SQL tables can have one column and a
primary key, neither of which can be named. •So, PL/SQL tables make it easy to move

collections of data into and out of database
The column can belong to any scalar type, but tables or between client-side applications and
the primary key must belong to type
BINARY_INTEGER. stored subprograms.

• PL/SQL tables can consist of one simple •Rows in a PL/SQL table do not have to be
datatype or be defined as a type of record and is contiguous.
sometimes referred to as an Index by table.
PL/SQL Decision Making Statements
• Decision-making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.

Statement Description
The IF statement associates a condition with a sequence of statements enclosed by the
IF - THEN
keywords THEN and END IF. If the condition is true, the statements get executed and if
statement
the condition is false or NULL then the IF statement does nothing.

IF statement adds the keyword ELSE followed by an alternative sequence of statement. If


IF-THEN-ELSE
the condition is false or NULL , then only the alternative sequence of statements get
statement
executed. It ensures that either of the sequence of statements is executed.

IF-THEN-ELSIF
It allows you to choose between several alternatives.
statement
Like the IF statement, the CASE statement selects one sequence of statements to execute.
However, to select the sequence, the CASE statement uses a selector rather than multiple
Case statement
Boolean expressions. A selector is an expression whose value is used to select one of several
alternatives.

Searched CASE The searched CASE statement has no selector, and it's WHEN clauses contain search
statement conditions that yield Boolean values.
nested IF-THEN- You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or IF-
ELSE THEN-ELSIF statement(s).
PL/SQL IF - THEN statement Example 1
PL/SQL IF - THEN statement Example 2
PL/SQL IF-THEN-ELSE statement Example
PL/SQL IF-THEN-ELSIF statement Example
PL/SQL Case statement Example
PL/SQL Searched Case statement Example
PL/SQL nested IF-THEN-ELSE statement Example
PL/SQL Loops
Loop Control
Type
Description Description
Statement
The Exit statement
In this loop structure, sequence of statements completes the loop
PL/SQL is enclosed between the LOOP and END EXIT and control passes to
Basic LOOP statements. At each iteration, the statement the statement
LOOP sequence of statements is executed and then
immediately after
control resumes at the top of the loop.
END LOOP
Causes the loop to
skip the remainder of
PL/SQL Repeats a statement or group of statements
WHILE while a given condition is true. It tests the CONTINUE its body and
LOOP condition before executing the loop body. statement immediately retest its
condition prior to
reiterating.
Execute a sequence of statements multiple
PL/SQL Transfers control to
times and abbreviates the code that manages
FOR LOOP the labeled statement.
the loop variable.
GOTO Though it is not
Nested statement advised to use GOTO
You can use one or more loop inside any
loops in statement in your
another basic loop, while or for loop.
PL/SQL program.
Labeling loops
PL/SQL Basic LOOP Example 1
PL/SQL Basic LOOP Example 2
PL/SQL WHILE Loop Example
PL/SQL FOR Loop Example
PL/SQL NESTED Loops Example
PL/SQL Continue Example
PL/SQL GOTO Example
An error condition during a program execution is called an exception in PL/SQL.

PL/SQL supports programmers to catch such conditions using EXCEPTION block in the program and an appropriate action
is taken against the error condition.

There are two types of exceptions:


System-defined exceptions
User-defined exceptions
Syntax for Exception Definition & Raising
Exception Handling Example
User Defined Exception Example
Pre-Defined Exceptions
Exception Description
ACCESS_INTO_NULL It is raised when a null object is automatically assigned a value.
It is raised when none of the choices in the WHEN clauses of a CASE statement is selected, and
CASE_NOT_FOUND
there is no ELSE clause.

It is raised when a program attempts to apply collection methods other than EXISTS to an
COLLECTION_IS_NULL uninitialized nested table or varray, or the program attempts to assign values to the elements of
an uninitialized nested table or varray.

DUP_VAL_ON_INDEX It is raised when duplicate values are attempted to be stored in a column with unique index.

It is raised when attempts are made to make a cursor operation that is not allowed, such as
INVALID_CURSOR
closing an unopened cursor.
It is raised when the conversion of a character string into a number fails because the string does
INVALID_NUMBER
not represent a valid number.
It is raised when s program attempts to log on to the database with an invalid username or
LOGIN_DENIED
password.
NO_DATA_FOUND It is raised when a SELECT INTO statement returns no rows.

NOT_LOGGED_ON It is raised when a database call is issued without being connected to the database.
PROGRAM_ERROR It is raised when PL/SQL has an internal problem.
ROWTYPE_MISMATCH It is raised when a cursor fetches value in a variable having incompatible data type.
It is raised when a member method is invoked, but the instance of the object type was not
SELF_IS_NULL
initialized.
STORAGE_ERROR It is raised when PL/SQL ran out of memory or memory was corrupted.
TOO_MANY_ROWS It is raised when s SELECT INTO statement returns more than one row.

VALUE_ERROR It is raised when an arithmetic, conversion, truncation, or size-constraint error occurs.

ZERO_DIVIDE It is raised when an attempt is made to divide a number by zero.


Exception propagation
• When an exception is raised by PL/SQL and if it not handled in the
current block then the exception is propagated.
▫ That means, the exception is sent to enclosing blocks one after another
from inside to outside until an error handler is found in one of the
enclosing blocks or there are no more blocks to search for handlers.

• When an exception is not handled in any of the enclosing blocks


then it is sent to host environment.
Reraising an exception
• RAISE command can also be used to reraise an exception so that the current
exception is propagated to outer block.

• If a sub block executes RAISE statement without giving exception name in


exception handler then the current exception is raised again.
A subprogram is a program unit/module that performs a
particular task.

These subprograms are combined to form larger programs. This


is basically called the 'Modular design'.

A subprogram can be invoked by another subprogram or


program which is called the calling program.

A subprogram can be created:


At schema level
Inside a package
Inside a PL/SQL block
PL/SQL Subprograms Types
• PL/SQL subprograms are named PL/SQL blocks that can be invoked with a
set of parameters.

1. A schema level subprogram is a standalone subprogram.


 It is created with the CREATE PROCEDURE or CREATE FUNCTION statement.
 It is stored in the database and can be deleted with the DROP PROCEDURE or
DROP FUNCTION statement.

2. A subprogram created inside a package is a packaged subprogram.


 It is stored in the database and can be deleted only when the package is deleted with
the DROP PACKAGE statement.

• A stored subprogram is either a package subprogram or a standalone


subprogram.

• PL/SQL provides two kinds of subprograms:


▫ Functions: these subprograms return a single value, mainly used to compute
and return a value.
▫ Procedures: these subprograms do not return a value directly, mainly used to
perform an action.
Creating a PL/SQL Procedure

• procedure-name specifies the name of the procedure.

• [OR REPLACE] option allows modifying an existing procedure.

• The optional parameter list contains name, mode and types of the parameters.
▫ IN represents that value will be passed from outside and
▫ OUT represents that this parameter will be used to return a value outside of the
procedure.

• procedure-body contains the executable part.

Note: The AS keyword is used instead of the IS keyword for creating a standalone
procedure.
PL/SQL Procedure Example
Parameter Modes
Mode Parameter Mode & Description

An IN parameter lets you pass a value to the subprogram.


It is a read-only parameter.
Inside the subprogram, an IN parameter acts like a constant.
It cannot be assigned a value.
IN You can pass a constant, literal, initialized variable, or expression as an IN parameter.
You can also initialize it to a default value; however, in that case, it is omitted from
the subprogram call.
It is the default mode of parameter passing.
Parameters are passed by reference.

An OUT parameter returns a value to the calling program.


Inside the subprogram, an OUT parameter acts like a variable.
OUT
You can change its value and reference the value after assigning it.
The actual parameter must be variable and it is passed by value.
An IN OUT parameter passes an initial value to a subprogram and returns an
updated value to the caller.
It can be assigned a value and its value can be read.
IN OUT The actual parameter corresponding to an IN OUT formal parameter must be a
variable, not a constant or an expression.
Formal parameter must be assigned a value.
Actual parameter is passed by value.
IN Parameter Mode and OUT Parameter Mode Example
IN OUT Parameter Mode Example
PL/SQL Functions

• A PL/SQL function is same as a procedure except that it returns a value.

• A standalone function is created using the CREATE FUNCTION statement.

• function-name specifies the name of the function.


• [OR REPLACE] option allows modifying an existing function.
▫ The optional parameter list contains name, mode and types of the parameters.
▫ IN represents that value will be passed from outside and
▫ OUT represents that this parameter will be used to return a value outside of the
procedure.
• The function must contain a return statement.
▫ RETURN clause specifies that data type you are going to return from the function.

• function-body contains the executable part.

Note: The AS keyword is used instead of the IS keyword for creating a


standalone function.
Calling a Function
Fibonacci Series Procedure
Rectangle Area Function
create or replace function find_area
(Len in number, Wid in number)
return number
as
varea number;
begin
varea := Len * Wid;
return varea;
end;
SQL> select find_area (10, 30) area from dual;
AREA
---------
300
PL/SQL Recursive Functions
• A program or subprogram may
call another subprogram.
• When a subprogram calls itself,
it is referred to as a recursive
call and the process is known as
recursion.
Oracle Instance Architecture
SGA and PGA

Potrebbero piacerti anche