0% found this document useful (0 votes)
60 views

Introduction To PL/SQL: Stone Apple Solutions Pte LTD

This document provides an agenda and introduction to PL/SQL. It outlines topics to be covered over two days, including PL/SQL introduction, advantages, block structure, data types, variables and scope, DML, conditional control, loops, case statements, and exceptions. It describes PL/SQL as a procedural language extension of SQL designed for database activities. It notes several advantages of PL/SQL, such as error handling, declaring variables, and portability. It also provides details on PL/SQL block structure and its required and optional components.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Introduction To PL/SQL: Stone Apple Solutions Pte LTD

This document provides an agenda and introduction to PL/SQL. It outlines topics to be covered over two days, including PL/SQL introduction, advantages, block structure, data types, variables and scope, DML, conditional control, loops, case statements, and exceptions. It describes PL/SQL as a procedural language extension of SQL designed for database activities. It notes several advantages of PL/SQL, such as error handling, declaring variables, and portability. It also provides details on PL/SQL block structure and its required and optional components.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 109

Introduction to PL/SQL

Stone Apple Solutions Pte Ltd

2/28/2018 1
Agenda
Day 3
• PL/SQL Introduction
• PL/SQL Advantages
• PL/SQL Block Structure
• PL/SQL Data Type
• PL/SQL Variable & Scope
• PL/SQL DML
Day 4
• PL/SQL Conditional Control
• PL/SQL Loop Statement
• PL/SQL Case Statement
• PL/SQL Cursor
• PL/SQL Exception
Introduction PL/SQL
PL/SQL Advantages
PL/SQL is a Procedural Language extension of Structured
Query Language (SQL).
PL/SQL is specially designed for Database oriented activities.
Oracle PL/SQL allows you to perform data manipulation
operation those are safe and flexible.
PL/SQL is a very secure functionality tool for manipulating,
controlling, validating, and restricting unauthorized access
data from the SQL database.
Using PL/SQL we can improve application performance. It
also allows to deal with errors so we can provide user friendly
error messages.
PL/SQL have a great functionality to display multiple records
from the multiple tables at the same time.
PL/SQL Advantages
PL/SQL is capable to send entire block of statements and execute it in
the Oracle engine at once.

Advantages PL/SQL
• Procedural language support : PL/SQL is a development tools not
only for data manipulation futures but also provide the
conditional checking, looping or branching operations same as like
other programming language.
• Reduces network traffic : This one is great advantages of PL/SQL.
Because PL/SQL nature is entire block of SQL statements execute
into oracle engine all at once so it's main benefit is reducing the
network traffic.
• Error handling : PL/SQL is dealing with error handling, It's permits
the smart way handling the errors and giving user friendly error
messages, when the errors are encountered.
PL/SQL Advantages
• Declare variable : PL/SQL gives you control to declare
variables and access them within the block. The
declared variables can be used at the time of query
processing.
• Intermediate Calculation : Calculations in PL/SQL done
quickly and efficiently without using Oracle engines.
This improves the transaction performance.
• Portable application : Applications are written in
PL/SQL are portable in any Operating system. PL/SQL
applications are independence program to run any
computer.
PL/SQL Block Structure
PL/SQL Block Structure
PL/SQL Block Structure
PL/SQL is block structured language divided into
three logical blocks.
BEGIN block and END; keyword are compulsory,
and other two block DECLARE and EXCEPTION
are optional block. END; is not a block only
keyword to end of PL/SQL program.
PL/SQL block structure follows divide-and-
conquer approach to solve the problem
stepwise.
PL/SQL Block Structure

DECLARE
Variables and constants are declared, initialized within this section.
Variables and Constants : In this block, declare and initialize variables (and
constants). You must have to declare variables and constants in declarative
block before referencing them in procedural statement.
PL/SQL Block Structure
Declare Variables and Assigning values : You can
define variable name, data type of a variable
and its size. Date type can be: CHAR, VARCHAR2,
DATE, NUMBER, INT or any other.
PL/SQL Block Structure
Declare Constants and Assigning values :
Constants are declared same as variable but you
have to add the CONSTANT keyword before
defining data type. Once you define a constant
value you can't change the value.
PL/SQL Block Structure
BEGIN/END
BEGIN block is procedural statement block
which will implement the actual programming
logic. This section contains conditional
statements (if...else), looping statements (for,
while) and Branching Statements (goto) etc.
PL/SQL Block Structure
EXCEPTION
PL/SQL easily detects user defined or predefined
error condition. PL/SQL is famous for handling
errors in smart way by giving suitable user
friendly messages. Errors can be rise due to
wrong syntax, bad logical or not passing a
validation rules.
PL/SQL Block Structure
You can also define exception in your declarative block and later you can
execute it by RAISE statement.

Note :
BEGIN block and END; keyword are compulsory of any PL/SQL program.
Where as DECLARE and EXCEPTION block are optional.
PL/SQL Block Structure
PL/SQL Block Structure
• Procedure and Function Can be call through
Anonymous Block
Ini contoh yang prosedure
Begin
my_procedure(<argument>);
End;

Ini yang contoh function


Declare
v_variable varchar2(10)
Begin
v_variable := my_function(<argument>);
End;
Exercise
1. Run the following procedure through anonymous block :
Begin
test_procedure('Hello Word ');
End;

2. Run the following Function through anonymous block :


Declare
v_variable VARCHAR2(40);
Begin
v_variable := test_function(‘Hello Word’);
dbms_output.put_line(v_variable);
End;
PL/SQL Data Types
PL/SQL Data Types
Every PL/SQL variable has a data type, which specifies a storage format, constraints, and a valid
range of values. PL/SQL supports several data type categories, including scalar, reference,
large object (LOB), and composite.

• Scalar data types: -> single value like varchar, numeric


Scalar data types hold a single value. The value depends on the data
type of the variable. For example, the v_myName variable in the example in the section
“Declaring and Initializing PL/SQL Variables” (in this lesson) is of type VARCHAR2.
Therefore, v_myName can hold a string value. PL/SQL also supports Boolean variables.

• LOB data types -> binary


LOB data types hold values, called locators, which specify the location of large objects (such
as graphic images) that are stored outside the table.

• Composite data types: ->


Composite data types are available by using PL/SQL collection
and record variables. PL/SQL collections and records contain internal elements that you
can treat as individual variables.
PL/SQL Data Types
PL/SQL Data Types
PL/SQL Data Types
PL/SQL Data Types
PL/SQL Data Types
PL/SQL Data Types
PL/SQL Data Types
PL/SQL Data Types
PL/SQL Data Types
Boolean Data types
Boolean Data types stores logical values either TRUE or
FALSE. Let's see Boolean data types in PL/SQL:

Data Types Description


BOOLEAN Boolean data type stores logical values. Boolean data types
doesn't take any parameters.
Boolean data type store either TRUE or FALSE. Also store NULL,
Oracle treats NULL as an unassigned boolean variable.
You can not fetch boolean column value from another table.
PL/SQL Variable
PL/SQL Variable
PL/SQL Variable
PL/SQL Variable
PL/SQL Variable
Example:
PL/SQL Variable
PL/SQL Variable
PL/SQL Variable
PL/SQL Variable
PL/SQL Variable
PL/SQL Variable
Example:
Exercise
Exercise:
Create PL/SQL Data Type by using ‘%type’ to show all data on orders table.
The output should be like below for column order_number , order_date,
amount:
PL/SQL Variable & Scope
PL/SQL Variable & Scope
PL/SQL variable declaration always specifies the variable name, data type of
variable and size. In PL/SQL variable declaration you can also specifies initial
value of declared variables.

Variable Declaration Syntax


The general syntax to declare a variable is:
variable_name Datatype[Size] [NOT NULL] := [ value ];
Explanation:
• Variable_name is the predefined name of the variable.
• Data type is a valid PL/SQL data type.
• Size is an optional specification of data type size to hold the maximum size
value.
PL/SQL Variable & Scope
• NOT NULL is an optional specification of the variable value can't be accept
NULL.
• value is also an optional specification, where you can initialize the initial
value of variable.
• Each variable declaration is terminated by a semicolon.

Variable Declaration Example


In this example variable defining employee number (eno) is NOT
NULL(compulsory), employee name and initializing initial value to a variable,
PL/SQL Variable & Scope

Variables Scope
PL/SQL variable scope is identified the region range
which you can reference the variable. PL/SQL have
two type scopes local scope and global scope,
PL/SQL Variable & Scope

Variable Scope Example


In this example declaration two variables (num1
and num2) are in the outer block (Global
variable) and another one third variable
declared (num_addition) into the inner block
(local variable). Variable 'num_addition'
declared inner block so can't access in the outer
block. But num1 and num2 can be accessed
anywhere in the block.
PL/SQL Variable & Scope
Exercise

Create PL/SQL Variable & Scope to grouping first


name and last name. Variable ‘A’ is first name
and variable ‘B’ is last name.
The output should be like below.
Exercise
Exercise:

Create PL/SQL program to display


PL/SQL DML
PL/SQL DML
PL/SQL DML
PL/SQL DML
PL/SQL DML
PL/SQL DML

• Transaction Control
– COMMIT
– ROLLBACK
Exercise

1. Create EMP_STUDENT<no> table with the


same structure with table EMP
2. Create PL/SQL with the following logic
a. always clear the table before insert the
data from emp
b. Update the salary with additional 20%
with the original salary.
PL/SQL DML

PL/SQL Conditional Control


PL/SQL Conditional Control

PL/SQL IF THEN ELSE conditional control statements. PL/SQL


Conditional Control two type: IF THEN ELSE statement and
CASE statement,
PL/SQL IF statement check condition and transfer the
execution flow on that matched block depending on a
condition. IF statement execute or skip a sequence of one or
more statements. PL/SQL IF statement four different type,

• IF THEN Statement
• IF THEN ELSE Statement
• IF THEN ELSIF Statement
• Nested IF THEN ELSE Statement
PL/SQL Conditional Control

IF THEN Statement
IF THEN Statement write in following syntax format:
IF ( condition ) THEN
Statement
END IF;
Example
We declare one number with initialize 14 value is equal of condition value,
Comparing 2 values by using IF THEN statement,
PL/SQL Conditional Control

IF THEN ELSE Statement


IF THEN ELSE Statement write in following syntax format:
IF ( condition ) THEN
statement;
ELSE
statement;
END IF;

Example
Same as above example if condition not true then else part will execute.
PL/SQL Conditional Control

IF THEN ELSIF Statement


IF THEN ELSIF Statement write in following syntax format:
IF ( condition-1 ) THEN statement-1;
ELSIF ( condition-2 ) THEN statement-2;
ELSIF ( condition-3 ) THEN statement-3;
ELSE statement; END IF;
PL/SQL Conditional Control

Example
Here one student result example for archiving grade.
PL/SQL Conditional Control

Nested IF THEN ELSE Statement


Logically IF THEN ELSIF Statement and Nested IF THEN ELSE Statement both
are same. Nested IF THEN ELSE Statement write in following syntax format:
IF ( condition-1 ) THEN statement-1;
ELSE
IF ( condition-2 ) THEN
statement-2;
ELSE
IF ( condition-3 ) THEN
statements-3;
END IF;
END IF;
END IF;
PL/SQL Conditional Control

Example
Here check condition students gender male, if not male then finding the
result using nested IF THEN ELSE statement.
PL/SQL Conditional Control

Exercise:
Create PL/SQL program to Check student passing grade. If value between 9
and 10 then ‘A grade’, if value between 7 and 8 then ‘B grade’, if value is 6
then ‘C grade’, and others is ‘D grade’. Let assume the value is ‘7’.
Put the passing grade value in declare variable

The output should be like below:


PL/SQL Loop Statement
PL/SQL Loop Statement

PL/SQL Loop Basic Loop, FOR Loop, WHILE Loop


repeat a number of block statements in your
PL/SQL program. Loop use when we have a
block of statements for required to repeatedly
certain number of times. PL/SQL loop
statements 3 different forms:
• Basic LOOP
• WHILE LOOP
• FOR LOOP
PL/SQL Loop Statement
Basic LOOP
Basic LOOP write in following syntax format:
[ label_name ] LOOP
statement(s);
END LOOP [ label_name ];
PL/SQL Loop Statement
WHILE LOOP
WHILE LOOP write in following syntax format:
[ label_name ] WHILE condition LOOP statement(s);
END LOOP [ label_name ];
PL/SQL Loop Statement
FOR LOOP
FOR LOOP write in following syntax format:
[ label_name ] FOR current_value IN [ REVERSE ] lower_value..upper_value
LOOP
statement(s);
END LOOP [ label_name ];
Exercise
Exercise:
Create PL/SQL Loop Statement, loop until five times and add the iteration
with ‘1’.
The output should be like below:
Exercise

• Create Table with message_<student_no>


With 1 column number
• Insert the number into the table : 1 through
10 excluding 6 and 8
• Display the result as :
PL/SQL Case Statement
PL/SQL Case Statement

PL/SQL CASE statement comparing one by one


sequencing conditions. CASE statement attempt
to match expression that is specified in one or
more WHEN condition. CASE statement are
following two forms,

• Simple CASE Statement -> hanya berdasarkan


static value
• Searched CASE Statement
PL/SQL Case Statement
Simple CASE Statement
PL/SQL simple CASE statement evaluates selector and attempt to
match one or more WHEN condition.

Syntax
CASE selector
WHEN value-1
THEN statement-1;
WHEN value-2
THEN statement-2;
ELSE
statement-3;
END CASE
PL/SQL Case Statement

Simple Case Statement


PL/SQL Case Statement
Searched CASE Statement
PL/SQL searched CASE statement has not selector and attempt to match one
or more WHEN clauses condition.

Syntax
CASE WHEN condition-1 THEN
statement-1;
WHEN condition-2 THEN
statement-2;
ELSE
statement-3;
END CASE;
PL/SQL Case Statement

Searched Case Statement


PL/SQL Case Statement
Exercise:
Create PL/SQL Case Statement to check amount variable . If amount between
500 and 1000 then discount will be five percent and if amount more than
1000 then discount will be ten percent.

Result :
value of Amount : 1000 discount 5%
PL/SQL Cursor
PL/SQL Cursor
Cursor is the work area which Oracle reserves for
internal processing of SQL statements. This work
area is private for oracles reserved are called cursor.

Classification of CURSORS
Cursors can be classified as:
• Implicit Cursor or Internal Cursor : Manage for
Oracle itself or internal process itself.
• Explicit Cursor or User-defined Cursor : Manage
for user/programmer or external processing.
PL/SQL Implicit Cursor

Oracle uses implicit cursors for its internal


processing. Even if we execute a SELECT statement
or DML statement Oracle reserves a private SQL
area in memory called cursor.

Implicit Cursor Attributes


Following are implicit cursor attributes,

--ini untuk select statement


PL/SQL Implicit Cursor
Cursor Attribute Cursor Variable Description
%FOUND SQL%FOUND If SELECT statement return one or more rows or
DML statement (INSERT, UPDATE, DELETE)
affect one or more rows
If affect return TRUE otherwise return FALSE.
If not execute SELECT or DML statement return
NULL.
%NOTFOUND SQL%NOTFOUND If SELECT INTO statement return no rows and
fire no_data_found PL/SQL exception before
you can check SQL%NOTFOUND.
If not affect the row return TRUE otherwise
return FALSE.
PL/SQL Implicit Cursor

Cursor Attribute Cursor Variable Description


%ROWCOUNT SQL%ROWCOUNT Return the number of rows affected by a
SELECT statement or DML statement (insert,
update, delete).
If not execute SELECT or DML statement return
NULL.

Syntax
cursor_attribute ::=
{
cursor_name |
cursor_variable_name |
:host_cursor_variable_name
} % {FOUND | NOTFOUND | ROWCOUNT}
PL/SQL Implicit Cursor

Explanation :
• cursor_name : cursor_name identifies the
current scope which are previously declared.
• cursor_variable_name : cursor variable or
parameter identifies the current scope which are
previously declared.
• host_cursor_variable_name :
host_cursor_variable_name must be prefixed
with a colon. Host cursor variable datatype must
be compatible with the PL/SQL cursor variable.
PL/SQL Implicit Cursor

Example:
PL/SQL Implicit Cursor

Exercise:
Create PL/SQL Implicit Cursor to test whether item
name ‘Playstation’ exists on items table.
The output should be like below:
PL/SQL Explicit Cursor

Explicit Cursor which are construct/manage by user


itself call explicit cursor.
User itself to declare the cursor, open cursor to
reserve the memory and populate data, fetch the
records from the active data set one at a time,
apply logic and last close the cursor.
You can not directly assign value to an explicit
cursor variable you have to use expression or create
subprogram for assign value to explicit cursor
variable.
PL/SQL Explicit Cursor
PL/SQL Explicit Cursor
PL/SQL Explicit Cursor
PL/SQL Explicit Cursor
PL/SQL Explicit Cursor
PL/SQL Explicit Cursor

Example:
PL/SQL Explicit Cursor

Exercise:
Create PL/SQL explicit cursor to update existing amount by
adding ten percent on orders table.
The output should be like below:
PL/SQL Cursor For Loop

PL/SQL cursor FOR loop has one great advantage of


loop continued until row not found. In sometime you
require to use explicit cursor with FOR loop instead of
use OPEN, FETCH, and CLOSE statement.
FOR loop iterate repeatedly and fetches rows of values
from database until row not found.
PL/SQL Cursor For Loop

Explicit Cursor FOR LOOP Example:


PL/SQL Cursor For Loop
Exercise:
Create PL/SQL Cursor For Loop to retrieve all data on orders table.
The output should be like below:
PL/SQL Exception
PL/SQL Exception
PL/SQL exceptions are predefined and raised automatically into oracle
engine when any error occur during a program.
Each and every error has defined a unique number and message.
When warning/error occur in program it's called an exception to
contains information about the error.
In PL/SQL built in exceptions or you make user define exception.
Examples of built-in type (internally) defined exceptions division by
zero, out of memory. Some common built-in exceptions have
predefined names such as ZERO_DIVIDE and STORAGE_ERROR.
Normally when exception is fire, execution stops and control transfers
to the exception-handling part of your PL/SQL block. Internal
exceptions are raised implicitly (automatically) by the run-time system.
User-defined exceptions must be raised explicitly by RAISE statements,
which are also raise predefined exceptions.
PL/SQL Exception
PL/SQL built in exceptions
Following are built in type exception,

Exception Error Code Description


CURSOR_ALREADY_OPEN ORA-06511 Exception raised when you open a cursor
that is already opened.
Exception raised when you store duplicate
DUP_VAL_ON_INDEX ORA-00001
value in unique constraint column.
Exception raised when you perform
INVALID_CURSOR ORA-01001 operation on cursor and cursor is not really
opened.
Exception raised when SELECT ... INTO
NO_DATA_FOUND ORA-01403 statement doesn't fetch any row from a
database table.
PL/SQL Exception
Exception Error Code Description
Exception raised when SELECT ... INTO statement
TOO_MANY_ROWS ORA-01422
returns more than one row.
Exception raised when you program try to
ZERO_DIVIDE ORA-01476
attempt divide by zero number.
Exception raised when you try to explicitly
INVALID_NUMBER ORA-01722
conversion from string to a number fail.
PL/SQL Exception
PL/SQL exceptions consist following three,
• Exception Type
• Error Code
• Error Message

Syntax
DECLARE
declaration statement(s);
BEGIN
statement(s);
EXCEPTION
WHEN built-in_exception_name_1 THEN
User defined statement (action) will be taken;
WHEN built-in_exception_name_2 THEN
User defined statement (action) will be taken;
END;
PL/SQL Exception
Example:
PL/SQL Exception
• To get detail error
from SQLERRM variable

Begin
---
Exception
when others then
dbms_output.put_line(SQLERRM);
End;
Exercise
Exercise:
Create PL/SQL Exception with ‘Too_many_rows’.
The output should be like below:
Exercise
Exercise:
Create PL/SQL Exception with ‘OTHERS’.
Display the error using SQLERRM

You might also like