Updates - Lec 5
Updates - Lec 5
Lec 5
1
Chapter Outline
PL/SQL Architecture
PL/SQL Data types
Variables, Identifiers and Naming convention
PL/SQL BLOCK
PL/SQL-Conditional Statements
PL/SQL-Loop statements
PL/SQL- Varray
PL/SQL –Stored procedures and Functions
Triggers
2
Introduction
3
PL/SQL Architecture
4
PL/SQL Architecture(contd.)
PL/SQL Block:
PL/SQL block creates the structured logical blocks of code that describes the
process to be executed. Such a block consists of SQL statements and PL/SQL
instructions that are then passed to the oracle engine for execution.
PL/SQL Engine:
The PL/SQL block containing the procedural statements are executed by the
PL/SQL statement executor inside the PL/SQL engine. In simpler words, the
PL/SQL engine provides the environment in which the PL/SQL block is executed.
Database Server:
This can be Oracle DB server or MySQL DB server. The DB server stores data in
tables.
5
PL/SQL Architecture(contd.)
6
Difference between PL/SQL and SQL
SQL statement
• When is issued on the client computer, the request is made to the database on the
server, and the result set is sent back to the client
• As a result, a single SQL statement causes two trips on the network.
• If multiple SELECT statements are issued, the network traffic increase significantly
very fast. For example, four SELECT statements cause eight network trips.
• they are sent to the server as a single unit. The SQL statements in this PL/SQL
program are executed at the server and the result set is sent back as a single unit.
There is still only one network trip made as is in case of a single SELECT statement.
7
Comparison of SQL* PLUS and PL/SQL
8
PL/SQL DATA TYPES
• The PL/SQL variables, constants and parameters must have a valid data
type, which specifies a storage format, constraints, and a valid range of
values.
9
PL/SQL DATA TYPES(contd.)
The scalar types are types that store single values such
as number Boolean, character, and date time
The composite types are types that store multiple values, for
example, record and collection.
The LOB Data Type is mainly used to store and manipulate
large blocks of unstructured data's like images, multimedia
files, etc
The Reference Data type is used to hold pointer values which
generally stores address of other program items.
10
PL/SQL DATA TYPES(contd.)
• Most commonly used Data Types are
11
CHARACTER Data Type
• This data type basically stores alphanumeric characters in string format.
• The literal values should always be enclosed in single quotes while
assigning them to CHARACTER data type.
• This character data type is further classified as follows:
CHAR Data type (fixed string size)
VARCHAR2 Data type (variable string size)
VARCHAR Data type
NCHAR (native fixed string size)
NVARCHAR2 (native variable string size)
LONG and LONG RAW
12
NUMBER Data Type
This data type stores fixed or floating point numbers up to 38 digits of
precision. This data type is used to work with fields which will contain only
number data
The variable can be declared either with precision and decimal digit details
or without any restrictions.
Syntax:
A NUMBER(8,2);
B NUMBER(8);
C NUMBER;
In the above, the first declaration declares the variable 'A' is of number data
type with total precision 8 and decimal digits 2.
13
NUMBER Data Type(contd.)
• The second declaration declares the variable 'B' is of number
data type with total precision 8 and no decimal digits
• The third declaration is the most generic, declares variable 'C'
is of number data type with no restriction in precision or
decimal places. It can take up to a maximum of 38 digits.
14
BOOLEAN Data Type
• This data type stores the logical values. It represents either TRUE or
FALSE and mainly used in conditional statements. Values need not enclose
within quotes while assigning for this data type.
Syntax:
Var1 BOOLEAN;
In the above Syntax, variable 'Var1' is declared as BOOLEAN data type. The
output of the code will be either true or false based on the condition set.
15
DATE Data Type
• This data type stores the values in date format, as date, month, and year. Whenever a
variable is defined with DATE data type along with the date it can hold time
information and by default time information is set to 12:00:00 if not specified. Values
need to enclose within quotes while assigning for this data type.
newyear DATE:='01-JAN-2020';
current_date DATE:=SYSDATE;
• In the above, variable 'newyear' is declared as DATE data type and assigned the value
of Jan 1st, 2020 date.
• The second declaration declares the variable current date as DATE data type and
assigned the value with current system date.
• Both these variable holds the time information.
16
LOB Data Type
• Oracle prefers LOB instead of the a LONG data type as it is more flexible
than the LONG data type
17
LOB Data Type(Contd.)
• CLOB and NCLOB:
CLOB data type stores the LOB data into the character set, whereas NCLOB
stores the data in the native character set. Since these data types use character
set based storage, these cannot store the data like multimedia, images, etc. that
cannot be put into a character string. The maximum size of these data types is
128 TB.
Syntax:
Charac_data CLOB;
In the above, variable 'Charac_data' is declared as CLOB data type.
18
LOB Data Type(Contd.)
• BFILE
BFILE are the data types that stored the unstructured binary format data
outside the database as an operating-system file.
The size of BFILE is to a limited operating system, and they are read-only
files and can't be modified.
19
PL/SQL Delimiters
Delimiter Description
+, -, *, / Addition, subtraction/negation,
multiplication, division
% Attribute indicator
. Component selector
, Item separator
= Relational operator
20
Declare Variables, identifiers , Naming conventions in
PL/SQL
• Identifiers:
Identifiers is a name that is given to a PL/SQL object. The object could be constant,
variable, exception, cursors, procedures, function, package, trigger, object type,
reserve word or label.
• Properties of Identifiers:
Must start with a letter
Maximum size is limited to 30 letters
Cannot contain whitespace characters
Can contain dollar sign ('$'), underscore ('_') and hash sign ('#')
Is case-insensitive
21
Declare Variables, identifiers , Naming conventions in
PL/SQL(contd.)
22
Declaration of Variables
Declaration of variables:
• Variables are mainly used to store data during the data manipulation or data
processing.
• They need to be declared before using them inside the program.
• This declaration needs to be done in the declarative section of the PL/SQL
blocks.
• Declaration of variables is a process of assigning the name to the placeholder
and associate the same with a valid data type.
Syntax :
<variable name> <data type>;
The above syntax shows how to declare the variable in the declarative section.
23
Data storing in Variables
• Once the variable is declared, they are ready to hold the data of defined type. The
values of these variables can be assigned either in execution section or at the time
of declaring itself.
Syntax: variable_name data type := default_value;
The above syntax shows how to declare the variable and assign value in the
declarative section.
Syntax:
variable_name data type;
variable name := value;
The above syntax shows how to assign the value to an already declared variable.
24
Example
Explanation of example:
Code line 2: Declaring the variable
'lv_name' of VARCHAR2 with size 50.
Code line 3: Declaring the variable
DECLARE
'lv_name_2' of VARCHAR2 with size 50 and lv_name VARCHAR2(50);
assigned the default value using literal lv_name_2 VARCHAR2(50) := ‘WAFA';
‘WAFA'. BEGIN
Code line 5: Value for variable 'lv_name' has lv_name := lv_name_2;
dbms_output .put_line(lv_name);
been assigned from the variable 'lv_name_2'. END ;
Code line 6: Printing the stored value of /
variable 'lv_name'.
When the above code is executed, you will get
the following output.
Output: WAFA
25
PL/SQL BLOCK
In a PL/SQL program, code is written in blocks. Each PL/SQL block has 3
sections, which are:
Declare section
Begin section
Exception section
26
PL/SQL Block STRUCTURE
Example:
DECLARE
v_first_name VARCHAR2(35) ;
v_last_name VARCHAR2(35) ;
v_counter NUMBER := 0 ;
28
EXECUTABLE SECTION
This section is enclosed between the keywords BEGIN and END and it is a
mandatory section.
This section contains executable statements that allow you to manipulate
the variables that have been declared in the declaration section
BEGIN
SELECT first_name, last_name
INTO v_first_name, v_last_name
FROM student
WHERE student_id = 123 ;
DBMS_OUTPUT.PUT_LINE
(‘Student name :’ || v_first_name ||‘ ’|| v_last_name);
END;
/
29
EXCEPTION HANDLING SECTION
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE
(‘ There is no student with student id 123 ’);
END;
30
Anonymous PL/SQL Blocks
PL/SQL blocks are a part of large programs and are either sub-programs, or
functions, or procedures, or triggers etc., but they can be defined independently
and can be executed as well.
When PL/SQL block is defined with no header , it is known as Anonymous Block
Example:
DECLARE
-- declare variable a and b Output:
-- and these variables have integer datatype 84
a number;
b number;
BEGIN
a:= 7;
b:= 77;
dbms_output.put_line('Sum of the number is: ' || a + b);
END;
/ 31
The PL/SQL Comments
32
Example
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be
nested within other PL/SQL blocks using BEGIN and END. Following is the
basic structure of a PL/SQL block −
DECLARE
message varchar2(20):= 'Hello World!';
BEGIN
dbms_output.put_line(message);
END;
/
33
Example
Hello World
PL/SQL procedure successfully completed.
34
Oracle PL/SQL IF THEN ELSE Statement: ELSIF,
NESTED-IF
Decision making statements are those who will decide the
flow-control of SQL statements based on the conditions.
PL/SQL programming language provides following types of
decision-making statements
If Statement
If...then...else statement
If...then...elsif...else statement
Case Statement
Searched Case Statement
35
PL/SQL: if Statement
36
36
Example : if Statement
37
PL/SQL: if...then...else statement
38
Example if...then...else
39
PL/SQL: if...then...elsif...else statement
The IF-THEN-ELSIF statement is mainly used where one alternative should be chosen from a set
of alternatives, where each alternative has its own conditions to be satisfied.
The IF-THEN-ELSIF statement may contain 'ELSE' block in it. This 'ELSE' block will be executed if
none of the conditions is satisfied.
Syntax for IF-THEN-ELSIF Statements:
if <test_condition1> then
body of action
elsif <test_condition2>then
body of action
elsif<test_condition3>then
body of action
...
....
else body of action
end if;
.
40
Example: if...then...elsif...else statement
41
PL/SQL: Case Statement
42
Example: Case Statement
43
PL/SQL: Searched Case Statement
The searched CASE statement has no selector, and it's WHEN clauses
contain search conditions that yield Boolean values.
Syntax:
CASE
when <test_condition1> then statement1;
when <test_condition2> then statement2;
...
...
else default statement;
end case;
44
Example: Searched Case Statement
dt := '&dt';
str := to_char(dt,'DY');
CASE
when str in ('SAT','SUN') then dbms_output.put_line('Its the Weekend');
else dbms_output.put_line('Not a Weekend');
END CASE;
END;
/ 45
PL/SQL Loops
Basic Loop
While Loop
For Loop
46
Slide
8- 47
PL/SQL Loops
Basic Loop:
Basic loop or simple loop is preferred in PL/SQL code when there
is no surety about how many times the block of code is to be
repeated
Simple loop always begins with the keyword LOOP and ends with
a keyword END LOOP.
A basic/simple loop can be terminated at any given point by using
the exit statement or by specifying certain condition by using the
statement exit when.
47
PL/SQL: Basic Loop(Example)
Syntax:
LOOP
sequence of statements
END LOOP;
Example:
set serveroutput on; Output:
1
DECLARE 2
i int; 3
BEGIN 4
5
i := 1; 6
LOOP 7
if i>10 then 8
9
exit; 10
end if; PL/SQL procedure successfully completed
dbms_output.put_line(i);
i := i+1;
END LOOP;
END;
/
48
PL/SQL : While Loop
49
Example: While Loop
Example:
Output:
set serveroutput on; 1
DECLARE 3
5
num int:=1; 7
9
BEGIN
PL/SQL procedure successfully completed.
while(num <= 10) LOOP
dbms_output.put_line(''|| num);
num := num+2;
END LOOP;
END;/
50
PL/SQL : For Loop
51
Example: For Loop
52
PL/SQL : Array- VARRAY
53
PL/SQL : Array- VARRAY
To access the data elements stored in a varray type variable, we use the
syntax variable_name(index) where index starts from 1 for the first element and
goes up to the current upper bound of elements which means the number of
elements that exists at that given point(not the maximum size of the array).
The upper bound keeps on changing as you add or remove elements from an array,
but it cannot exceed the maximum size of the array.
Example:
In the Below diagram below we have a varray Marks of size 8 and 5 data elements
are stored in it.
54
Varray
55
Example : Varray
56
Example: Varray
In the above example, we have declared two varray types one for storing student
names and another on for storing student's marks
And then we have used them in our PL/SQL block for storing student names and
student marks.
57
PL/SQL: Stored Procedure
Output:
Procedure created
59
Example: Stored Procedure
END;
/
60
PL/SQL : Function
61
PL/SQL : Function
62
Example: Function
63
Example : Function
64
Triggers
65
PL/SQL: Parts of Trigger
66
66
PL/SQL: Types of Trigger
67
PL/SQL: Types of Triggers
Event Triggers:
There are 3 different types of event triggers, they are:
• DDL EVENT TRIGGER: It fires with the execution of every DDL
statement(CREATE, ALTER, DROP, TRUNCATE).
• DML EVENT TRIGGER: It fires with the execution of every DML
statement(INSERT, UPDATE, DELETE).
• DATABASE EVENT TRIGGER: It fires with the execution of every
database operation which can be LOGON, LOGOFF,
SHUTDOWN, SERVERERROR etc.
68
PL/SQL: Types of Triggers
Event Triggers:
There are 3 different types of event triggers, they are:
• DDL EVENT TRIGGER: It fires with the execution of every DDL
statement(CREATE, ALTER, DROP, TRUNCATE).
• DML EVENT TRIGGER: It fires with the execution of every DML
statement(INSERT, UPDATE, DELETE).
• DATABASE EVENT TRIGGER: It fires with the execution of every
database operation which can be LOGON, LOGOFF,
SHUTDOWN, SERVERERROR etc.
69
PL/SQL: Types of Triggers
Timing Triggers:
There are 2 different types of timing triggers, they are:
BEFORE TRIGGER: It fires before executing DML
statement.
70
Trigger: Syntax and Example
Where
CREATE OR REPLACE TRIGGER is a keyword used to create a trigger and <trigger_name> is user-
defined where a trigger can be given a name.
BEFORE/AFTER/INSTEAD OF specify the timing of the trigger's occurrence.
INSTEAD OF is used when a view is created.
INSERT/UPDATE/DELETE specify the DML statement.
<table_name> specify the name of the table on which DML statement is to be applied.
REFERENCING is a keyword used to provide reference to old and new values for DML statements.
FOR EACH ROW is the clause used to specify row level trigger.
WHEN is a clause used to specify condition to be applied and is only applicable for row-level
trigger.
DECLARE, BEGIN, EXCEPTION, END are the different sections of PL/SQL code block containing
variable declaration, executable statements, error handling statements and marking end of
PL/SQL block respectively where DECLARE and EXCEPTION part are optional.
72
Example: Trigger
Output:
Trigger created
73
Example: Trigger
11 ALIYA 20 B.SC
12 Hanan 21 B.SC
13 Fatima 18 B.C.A
14 Hana 20 B.D.S
15 Nihal 19 M.D.S
74
Example: Trigger
After initializing the trigger CheckAge, whenever we will insert any new values
or update the existing values in the above table STUDENT our trigger will
check the age before executing INSERT or UPDATE statements and according
to the result of triggering restriction or condition it will execute the statement.
Example 1:
INSERT into STUDENT values(16, 'Saina', 32, 'BCOM');
75
Example: Trigger
76
Example 3:
UPDATE STUDENT set age=31 where ROLLNO=12;
Example 4:
UPDATE STUDENT set age=23 where ROLLNO=12;
76
Reference
77