Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
PL/SQL includes procedural language elements such as conditions and loops. It allows
declaration of constants and variables, procedures and functions, types and variables of those
types, and triggers. It can handle exceptions (run-time errors). Arrays are supported involving the
use of PL/SQL collections. Implementations from version 8 of Oracle Database on wards have
included features associated with object-orientation. One can create PL/SQL units such as
procedures, functions, packages, types, and triggers, which are stored in the database for reuse
by applications that use any of the Oracle Database programmatic interfaces.
Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part.
This is the section in which the declaration of variables, cursors, exceptions,
subprograms, pragma instructions and collections that are needed in the
block will be declared. Below are few more characteristics of this part.
Execution Section
Execution part is the main and mandatory part which actually executes the
code that is written inside it. Since the PL/SQL expects the executable
statements from this block this cannot be an empty block, i.e., it should have at
least one valid executable code line in it. Below are few more characteristics of
this part.
This can contain both PL/SQL code and SQL code.
This can contain one or many blocks inside it as a nested block.
This section starts with the keyword 'BEGIN'.
This section should be followed either by 'END' or Exception-Handling
section (if present)
Exception-Handling Section:
The exception is unavoidable in the program which occurs at run-time and to
handle this Oracle has provided an Exception-handling section in blocks. This
section can also contain PL/SQL statements. This is an optional section of the
PL/SQL blocks.
This is the section where the exception raised in the execution block is
handled.
This section is the last part of the PL/SQL block.
Control from this section can never return to the execution block.
This section starts with the keyword 'EXCEPTION'.
This section should always be followed by the keyword 'END'.
BEGIN --mandatory
<executable statements. At least one executable statement is mandatory>
EXCEPTION --optional
<exception handles>
END; --mandatory
/
Note: A block should always be followed by '/' which sends the information to
the compiler about the end of the block.
1. Anonymous blocks
2. Named Blocks
Anonymous blocks:
Anonymous blocks are PL/SQL blocks which do not have any names assigned
to them. They need to be created and used in the same session because they
will not be stored in the server as database objects.
Since they need not store in the database, they need no compilation steps.
They are written and executed directly, and compilation and execution
happen in a single process.
These blocks don't have any reference name specified for them.
These blocks start with the keyword 'DECLARE' or 'BEGIN'.
Since these blocks do not have any reference name, these cannot be
stored for later purpose. They shall be created and executed in the same
session.
They can call the other named blocks, but call to anonymous block is not
possible as it is not having any reference.
It can have nested block in it which can be named or anonymous. It can
also be nested in any blocks.
These blocks can have all three sections of the block, in which execution
section is mandatory, the other two sections are optional.
Named blocks:
Named blocks have a specific and unique name for them. They are stored as
the database objects in the server. Since they are available as database objects,
they can be referred to or used as long as it is present on the server. The
compilation process for named blocks happens separately while creating
them as a database objects.
1. Procedure
2. Function
We will learn more about these named blocks in "Procedure" and "Function"
topics in later tutorial.
Connecting to Database
To connect to Database First start Run SQL Command Line from start menu as Administrator
Then write following command to connect to SYSDBA “CONNECT / AS SYSDBA”
Now you can write your Blocks here
BEGIN
2 dbms_output.put_line (‘Hello World..');
3 END:
4 /
DECLARE
text VARCHAR2(25);
BEGIN
text:= ‘Hello World’;
dbms_output.put_line (text);
END:
/
Comments in PL/SQL
Commenting code simply instructs the compiler to ignore that particular code
from executing.
Using '--' in the beginning of the line to comment that particular line.
Using '/*…….*/' we can use multiple lines. The symbol '/*' marks the
starting of the comment and the symbol '*/' marks the end of the
comment. The code between these two symbols will be treated as
comments by the compiler.
Example: In this example, we are going to print 'Hello World' and we are also
going to see how the commented lines behave in the code
BEGIN
--single line comment
dbms output.put line (' Hello World ’);
/*Multi line commenting begins
Multi line commenting ends */
END;
/
The literal values should always be enclosed in single quotes while assigning
them to CHARACTER data type.
CHAR This data type stores the string value, grade CHAR;
and the size of the string is fixed at the manager CHAR (10):= 'guru99';
time of declaring the variable. Syntax Explanation:
VARCHAR2 This data type stores the string, but the manager VARCHAR2(10) := ‘guru99';
length of the string is not fixed. Syntax Explanation:
NCHAR This data type is same as CHAR data type, native NCHAR(10);
but the character set will of the national Syntax Explanation:
character set.
LONG and This data type is used to store large text Large_text LONG;
LONGRAW or raw data up to the maximum size of Large_raw LONG RAW;
2GB. Syntax Explanation:
A NUMBER(8,2);
B NUMBER(8);
C NUMBER;
Syntax Explanation:
In the above, the first declaration declares the variable 'A' is of number
data type with total precision 8 and decimal digits 2.
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.
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.
Var1 BOOLEAN;
Syntax Explanation:
This data type stores the values in date format, as date, month, and year.
Whenever DATE Data Type:
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.
The standard Oracle time format for input and output is 'DD-MON-YY' and it is
again set at NLS_PARAMETERS (NLS_DATE_FORMAT) at the session level.
newyear DATE:='01-JAN-2015';
current_date DATE:=SYSDATE;
Syntax Explanation:
So, it is always good to use LOB data type instead of the LONG data type.
Following are the different LOB data types. They can store up to the size of
128 terabytes.
1. BLOB
2. CLOB and NCLOB
3. BFILE
BLOB This data type stores the LOB data in the Binary_data BLOB;
binary file format up to the maximum size of
128 TB. This doesn't store data based on the Syntax Explanation:
character set details, so that it can store the
unstructured data such as multimedia objects, In the above, variable
CLOB and CLOB data type stores the LOB data into the Charac_data CLOB;
NCLOB character set, whereas NCLOB stores the data
in the native character set. Since these data Syntax Explanation:
types use character set based storage, these
cannot store the data like multimedia, images, In the above, variable
What is Identifiers?
Identifiers are nothing but 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
Naming Conventions of Identifiers
Variables – An Identifier
Declaration of Variables
Data storing in Variables
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
The first letter should be used to specify the declared level of the
variable. The below point give the different first letters and their
declarative level
o 'P' – Variable is declared at the parameter level
o 'L' – Variable is declared at the local block
o 'G' – Variable is declared at the global level
The second letter specifies the type of identifier. Below are the
commonly used identifier types and their naming code.
o 'C' – Cursor Identifier
o 'V' – Varchar and char datatype
o 'N' – Number datatype
o 'R' – Record type
o 'T' – Table type
Code Explanation:
Code line 2: Declaring the variable 'lv_name' of VARCHAR2 with size 50.
Code line 3: Declaring the variable 'lv_name_2' of VARCHAR2 with size
50 and assigned the default value using literal 'GURU99'.
Code line 5: Value for variable 'lv_name' has been assigned from the
variable 'lv_name_2'.
Code line 6: Printing the stored value of variable 'lv_name'.
When the above code is executed, you will get the following output.
Output:
GURU99
Oracle PL/SQL Collections: Varrays, Nested & Index by Tables
What is Collection?
A Collection is an ordered group of elements of particular data types. It can be
a collection of simple data type or complex data type (like user-defined or
record types).
Collections are most useful things when a large data of the same type need to
be processed or manipulated. Collections can be populated and manipulated
as whole using 'BULK' option in Oracle.
What is Collection?
Varrays
Nested Tables
Index-by-table
Constructor and Initialization Concept in Collections
Collection Methods
At any point, data in the collection can be referred by three terms Collection
name, Subscript, Field/Column name as
"<collection_name>(<subscript>).<column_name>". You are going to learn
about these above-mentioned collection categories further in the below
section.
Varrays
Varray is a collection method in which the size of the array is fixed. The array
size cannot be exceeded than its fixed value. The subscript of the Varray is of a
numeric value. Following are the attributes of Varrays.
The below figure will explain the memory allocation of Varray (dense)
diagrammatically.
Subscript 1 2 3 4 5 6 7
Nested Tables
A Nested table is a collection in which the size of the array is not fixed. It has
the numeric subscript type. Below are more descriptions about nested table
type.
The Nested table has no upper size limit.
Since the upper size limit is not fixed, the collection, memory needs to
be extended each time before we use it. We can extend the collection
using 'EXTEND' keyword.
Populated sequentially starting with the subscript '1'.
This collection type can be of both dense and sparse, i.e. we can create
the collection as a dense, and we can also delete the individual array
element randomly, which make it as sparse.
It gives more flexibility regarding deleting the array element.
It is stored in the system generated database table and can be used in
the select query to fetch the values.
The subscript and sequence are not stable, i.e. the subscript and the
count of the array element can vary.
They need to be initialized before using them in programs. Any
operation (except EXISTS operation) on the uninitialized collection will
throw an error.
It can be created as a database object, which is visible throughout the
database or inside the subprogram, which can be used only in that
subprogram.
The below figure will explain the memory allocation of Nested Table (dense
and sparse) diagrammatically. The black colored element space denotes the
empty element in a collection i.e. sparse.
Subscript 1 2 3 4 5 6 7
Index-by-table
Index-by-table is a collection in which the array size is not fixed. Unlike the
other collection types, in the index-by-table collection the subscript can
consist be defined by the user. Following are the attributes of index-by-table.
The below figure will explain the memory allocation of Nested Table (sparse)
diagrammatically. The black colored element space denotes the empty
element in a collection i.e. sparse.
Collection Methods
Oracle provides many functions to manipulate and to work with the
collections. These functions are very much useful in the program to determine
and to modify the different attribute of the collections. The Following table
will give the different functions and their description.
EXISTS This method will return Boolean results. It will return 'TRUE' <collection_name>.EXISTS(element_pos
(n) if the nth element exists in that collection, else it will return
FALSE. Only EXISTS functions can be used in uninitialized
collection
COUNT Gives the total count of the elements present in a collection <collection_name>.COUNT
LIMIT It returns the maximum size of the collection. For Varray, it <collection_name>.LIMIT
will return the fixed size that has been defined. For Nested
table and Index-by-table, it gives NULL
FIRST Returns the value of the first index variable(subscript) of the <collection_name>.FIRST
collections
LAST Returns the value of the last index variable(subscript) of the <collection_name>.LAST
collections
EXTEND Extends n copies of the ith element at the end of the <collection_name>.EXTEND(n,i)
(n,i) collection
TRIM Removes one element from the end of the collection <collection_name>.TRIM
TRIM (n) Removes n elements from the end of collection <collection_name>.TRIM (n)
DELETE Deletes all the elements from the collection. Makes the <collection_name>.DELETE
collection empty
DELETE Deletes the nth element from the collection. If the <collection_name>.DELETE(n)
(n) nth element is NULL, then this will do nothing
DELETE Deletes the element in the range mth to nth in the collection <collection_name>.DELETE(m,n)
(m,n)
In this example, we are going to see how to populate the collection using
'BULK COLLECT' and how to refer the collection data.
DECLARE
TYPE emp_det IS RECORD
(
EMP_NO NUMBER,
EMP_NAME VARCHAR2(150),
MANAGER NUMBER,
SALARY NUMBER
);
TYPE emp_det_tbl IS TABLE OF emp_det; guru99_emp_rec emp_det_tbl:= emp_det_tbl();
BEGIN
INSERT INTO emp (emp_no,emp_name, salary, manager) VALUES (1000,’AAA’,25000,1000);
INSERT INTO emp (emp_no,emp_name, salary, manager) VALUES (1001,'XXX’,10000,1000);
INSERT INTO emp (emp_no, emp_name, salary, manager) VALUES (1002,'YYY',15000,1000)
;
INSERT INTO emp (emp_no,emp_name,salary, manager) VALUES (1003,’ZZZ’,'7500,1000);
COMMIT:
Code line 2-8: Record type 'emp_det' is declared with columns emp_no,
emp_name, salary and manager of data type NUMBER, VARCHAR2,
NUMBER, NUMBER.
Code line 9: Creating the collection 'emp_det_tbl' of record type element
'emp_det'
Code line 10: Declaring the variable 'guru99_emp_rec' as 'emp_det_tbl'
type and initialized with null constructor.
Code line 12-15: Inserting the sample data into the 'emp' table.
Code line 16: Committing the insert transaction.
Code line 17: Fetching the records from 'emp' table and populating the
collection variable as a bulk using the command "BULK COLLECT". Now
the variable 'guru99_emp_rec' contains all the record that are present in
the table 'emp'.
Code line 19-26: Setting the 'FOR' loop using to print all the records in
the collection one-by-one. The collection method FIRST and LAST is
used as lower and higher limit of the loop.
Output: As you can see in the above screenshot when the above code is
executed you will get the following output
Employee Detail
Employee Number: 1000
Employee Name: AAA
Employee Salary: 25000
Employee Manager Number: 1000
----------------------------------------------
Employee Number: 1001
Employee Name: XXX
Employee Salary: 10000
Employee Manager Number: 1000
----------------------------------------------
Employee Number: 1002
Employee Name: YYY
Employee Salary: 15000
Employee Manager Number: 1000
----------------------------------------------
Employee Number: 1003
Employee Name: ZZZ
Employee Salary: 7500
Employee Manager Number: 1000
----------------------------------------------
In the first syntax, we can see the keyword 'CREATE TYPE' this instructs the
compiler to create the record type named "type_name_db" with the specified
column as a database object.
In the syntax, we are creating the record type named "type_name" only inside
the subprogram.
In both declaration method, the way of defining the column and data type is
similar.
In this program, we are going to see how to create "Record type" as a database
object. We are going to create record type 'emp_det' with four columns. The
columns and their data type are as follows:
EMP_NO (NUMBER)
EMP_NAME (VARCHAR2 (150))
MANAGER (NUMBER)
SALARY (NUMBER)
Code Explanation:
Output:
DECLARE
TYPE emp_det IS RECORD
(
EMP_NO NUMBER,
EMP_NAME VARCHAR2(150),
MANAGER NUMBER,
SALARY NUMBER
);
guru99_emp_rec emp_det;
BEGIN
guru99_emp_rec.emp_no:= 1001;
guru99_emp_rec.emp_name:=:'XXX';
guru99_emp_rec.manager:= 1000;
guru99_emp_rec.salary:=10000;
dbms_output.put.line('Employee Detail');
dbms_output.put_line ('Employee Number: '||guru99_emp_rec.emp_no);
dbms_output.put_line ('Employee Name: '||guru99_emp_rec.emp_name);
dbms_output.put_line ('Employee Salary: ' ||guru99_emp_rec.salary);
dbms_output.put_line ('Employee Manager Number: '||guru99_emp_rec.manager);
END;
/
Output:
Employee Detail
Employee Number: 1001
Employee Name: XXX
Employee Salary: 10000
Employee Manager Number: 1000
Code Explanation:
Code line 2-8: Record type 'emp_det' is declared with columns emp_no,
emp_name, salary and manager of data type NUMBER, VARCHAR2,
NUMBER, NUMBER.
Code line 9: guru99_emp_rec variable is declared as 'emp_det' data type.
Now this variable can hold the value that contains all the above 4
fields/columns.
Code line 11: Populating the 'emp_no' field of 'guru99_emp_rec' with
value 1001.
Code line 12: Populating the 'emp_name' field of 'guru99_emp_rec' with
value XXX.
Code line 13: Populating the 'manager' field of 'guru99_emp_rec' with
value 1000.
Code line 14: Populating the 'salary' field of 'guru99_emp_rec' with
value 10000.
Code line 15-19: Displaying the value of the 'guru99_emp_rec' in output.
Example 3: Record Type at Subprogram level-Row level access
DECLARE
TYPE emp_det IS RECORD
(
EMP_NO NUMBER,
EMP_NAME YARCHAR2( 150),
MANAGER NUMBER,
SALARY NUMBER
);
guru99_emp_rec emp_det;
BEGIN
INSERT INTO emp (emp_no, emp_name, salary, manager) VALUES (1002,'YYY',15000,1000)
;
COMMIT;
SELECT emp_no, emp_name, salary, manager INTO guru99_emp_rec FROM emp WHERE emp_no
=1002;
dbms_output.put_line (‘Employee Detail’);
dbms_output.put_line (‘Employee Number: '||guru99_emp_rec.emp_no);
dbms_output.put_line (‘Employee Name: '||guru99_emp_rec.emp_name);
dbms_output.put_line (‘Employee Salary: '||guru99_emp_rec. salary);
dbms_output.put_line (‘Employee Manager Number: '||guru99_emp_rec.manager);
END;
/
Code Explanation:
Code line 2-8: Record type 'emp_det' is declared with columns emp_no,
emp_name, salary and manager of data type NUMBER, VARCHAR2,
NUMBER, NUMBER.
Code line 9: guru99_emp_rec variable is declared as 'emp_det' data type.
Now this variable can hold the value that contains all the above 4
fields/columns.
Code line 11: Populating the table emp with data 1002 as emp_no, YYY
as emp_name, 15000 as salary and 1000 as manager number.
Code line 12: Committing the above insert transaction.
Code line 13: Populating the 'guru99_emp_rec' variable as a row level
data from the select query for employee number 1002.
Code line 15-19: Displaying the value of the 'guru99_emp_rec' in output.
Output:
Employee Detail
Employee Number: 1002
Employee Name: YYY
Employee Salary: 1000
Employee Manager Number: 15000
Note: The record type can be accessed only in column level while redirecting
its value to any output mode.
IF-THEN
IF-THEN-ELSE
IF-THEN-ELSIF
NESTED-IF
CASE
SEARCHED CASE
IF-THEN Statement
The IF-THEN statement is mainly used to execute a particular section of codes
only when the condition is satisfied.
Note: Whenever condition evaluated to 'NULL', then SQL will treat 'NULL' as
'FALSE'.
Example 1: In this example, we are going to print a message when the number
is greater than 100. For that, we will execute the following code
To print a message when a number has value more than 100, we execute the
following code.
DECLARE
a NUMBER :=10;
BEGIN
dbms_output.put_line(‘Program started.' );
IF( a > 100 ) THEN
dbms_output.put_line('a is greater than 100');
END IF;
dbms_output.put_line(‘Program completed.');
END;
/
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '10'.
Code line 4: Printing the statement "Program started".
Code line 5: Checking the condition, whether variable 'a' is greater than
'100.'
Code line 6: If 'a' is greater than '100', then "a is greater than 100" will
be printed. If 'a' is lesser than or equal to 100, then condition fails, so
the above printing statement ignored.
Code line 8: Printing the statement "Program completed".
Code Output:
Program started.
Program completed.
DECLARE
a CHAR(1) :=’u’;
BEGIN
IF UPPER(a) in ('A’,'E','I','0','U' ) THEN
dbms_output.put_line(‘The character is in English Vowels');
END IF;
END;
/
Code Explanation:
Code line 2: Declaring the variable 'a' as 'CHAR' of size '1' data type and
initializing it with value 'u'.
Code line 4: Checking the condition, whether variable 'a' is present in
the list ('A','E','I','O','U').
Value of 'a' has been converted to uppercase before comparing to make
the comparison is case-insensitive.
Code line 5: If 'a' is present in the list, then the statement "The character
is in English Vowels" will be printed. If condition failed, then this
program will not give any output, as outside the IF-THEN block we have
not issued any printing statement.
Code Output:
The character is in English Vowels
IF-THEN-ELSE Statement
The IF-THEN-ELSE statement is mainly used to select between two
alternatives based on the condition.
Below is the syntax representation of IF-THEN-ELSE statement.
Note: Whenever condition evaluates to 'NULL', then SQL will treat 'NULL' as
'FALSE'.
Example 1: In this example, we are going to print message whether the given
number is odd or even.
DECLARE
a NUMBER:=11;
BEGIN
dbms_output.put_line (‘Program started');
IF( mod(a,2)=0) THEN
dbms_output.put_line('a is even number' );
ELSE
dbms_output.put_line('a is odd number1);
END IF;
dbms_output.put_line (‘Program completed.’);
END;
/
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '11'.
Code line 4: Printing the statement "Program started".
Code line 5: Checking the condition, whether modulus of variable 'a' by
'2' is 0.
Code line 6: If '0', then "a is even number" will be printed.
Code line 7: If the modulus value is not equal to '0', then the condition
returns <FALSE>, so the message "a is odd number" will be printed.
Code line10: Printing the statement "Program completed"
Code Output:
Program started.
a is odd number
Program completed.
IF-THEN-ELSIF 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 first conditions that return <TRUE> will be executed, and the
remaining conditions will be skipped.
The IF-THEN-ELSIF statement may contain 'ELSE' block in it. This
'ELSE' block will be executed if none of the conditions is satisfied.
Note: Whenever condition evaluates to 'NULL', then SQL will treat 'NULL' as
'FALSE'.
In this example, we are going to print the grade based on the given marks
without else condition (mark >= 70 Grade A, mark >=40 and mark<70
Grade B, mark >=35 and mark<40 Grade C).
DECLARE
mark NUMBER :=55;
BEGIN
dbms_output.put_line(‘Program started.’ );
IF( mark >= 70) THEN
dbms_output.put_line(‘Grade A’);
ELSIF(mark >= 40 AND mark < 70) THEN
dbms_output.put_line(‘Grade B');
ELSIF(mark >=35 AND mark < 40) THEN
dbms_output.put_line(‘Grade C’);
END IF;
dbms_output.put_line(‘Program completed.’);
END;
/
Code Explanation:
Code line 2: Declaring the variable 'mark' as 'NUMBER' data type and
initializing it with value '55'.
Code line 4: Printing the statement "Program started".
Code line 5: Checking the condition1, whether 'mark' is greater or equal
70.
Code line 7: Since condition1 failed, then the condition2
'70>mark>=40' is checked.
Code line 8: The condtition2 returns <TRUE>, hence the message
'Grade B' will be printed.
Code line12: Printing the statement "Program completed".
In this case, the condition3 'mark < 35' will be skipped, as the controller
found one condition which returns <TRUE> before condition3.
Code Output:
Program started.
Grade B
Program completed.
In this example, we are going to print the grade based on the given marks with
else condition (mark >= 70 Grade A, mark >=40 and mark<70 Grade B,
mark >=35 and mark<40 Grade C, else 'No Grade').
DECLARE
mark NUMBER :=25;
BEGIN
dbms_output.put_line(‘Program started.’ );
IF( mark >= 70) THEN
dbms_output.put_line(‘Grade A’);
ELSIF(mark >= 40 AND mark < 70) THEN
dbms_output.put_line(‘Grade B');
ELSIF(mark >=35 AND mark < 40) THEN
dbms_output.put_line(‘Grade C);
ELSE
dbms_output.put_line(‘No Grade’);
END IF;
dbms_output.put_line(‘Program completed.' );
END;
/
Code Explanation:
Code line 2: Declaring the variable 'mark' as 'NUMBER' data type and
initializing it with value '25'.
Code line 4: Printing the statement "Program started".
Code line 5: Checking the condition 1, whether 'mark' is greater or equal
70.
Code line 7: Since condition1 failed, then the condition2
'70>mark>=40' is checked.
Code line 8: Since condition2 failed, then the condition3
'40>mark>=35' is checked.
Code line 11: Since all the conditions are failed, control will now check
for the presence of ELSE block, and it will print the message 'No Grade'
from ELSE block.
Code line14: Printing the statement "Program completed".
Code Output:
Program started.
No Grade
Program completed.
NESTED-IF Statement
The NESTED-IF statement is basically allowed programmers to place
one or more 'IF' condition inside another 'IF' condition's
<action_block> other than normal statements.
Each 'IF' condition should have a separate 'END IF' statement which
marks the end-of-scope of that particular <action_block>.
The 'IF' statement will consider the nearest 'END IF' statement as an
endpoint for that particular condition.
The pictorial representation for NESTED-IF is shown below diagram.
IF <conditionl: returns Boolean>
THEN
—executed only if the condition returns TRUE
<action block1 starts>
IF <condition2: returns Boolean>
THEN
<action_block2>
END IF; —END IF corresponds to condition2
<action_blockl ends>
END IF; —END IF corresponds to condition1
Syntax Explanation:
In the above syntax, the outer IF contains one more IF statement in its
action block.
The condition1 returns <TRUE>, then control will be executing
<action_block1> and checks the condition2.
If condition2 also returns <TRUE>, then <action_block2> will also be
executed.
In case of condition2 evaluates to <FALSE> then, SQL will skip the
<action_block2>.
In this example, we are going to print the greatest of three numbers by using
Nested-If statement. The numbers will be assigned in the declare part, as you
can see in the code below, i.e Number= 10,15 and 20 and the maximum
number will be fetched using nested-if statements.
DECLARE
a NUMBER :=10;
b NUMBER :=15;
c NUMBER :=20;
BEGIN
dbms_output.put_line(‘Program started.' );
IF( a > b)THEN
/*Nested-if l */
dbms_output.put_line(’Checking Nested-IF 1');
IF( a > c ) THEN
dbms_output.put_line(‘A is greatest’);
ELSE
dbms_output.put_line(‘C is greatest’);
END IF;
ELSE
/*Nested-if2 */
dbms_output.put_line('Checking Nested-IF 2' );
IF( b > c ) THEN
dbms_output.put_line(’B is greatest' );
ELSE
dbms_output.put_line(’C is greatest' );
END IF;
END IF;
dbms_output.put_line(‘Program completed.’ );
END;
/
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '10'.
Code line 3: Declaring the variable 'b' as 'NUMBER' data type and
initializing it with value '15'.
Code line 4: Declaring the variable 'c' as 'NUMBER' data type and
initializing it with value '20'.
Code line 6: Printing the statement "Program started" (line 6).
Code line 7: Checking the condition1, whether 'a' is greater than 'b' (line
7).
Code line 10: If 'a' is greater than 'b, then condition in 'nested-if 1' will
check if 'a' is greater than 'c'(line 10).
Code line 13: If still 'a' is greater, then message 'A is greatest' will be
printed (line 11). Else if condition2 fails, then 'C is greatest' will be
printed (line 13).
Code line 18: In case condition1 returns false, then condition in 'nested-
if 2' will check if 'b' is greater than 'c'(line 18).
Code line 21: If 'b' is greater than 'c' , then message 'B is greatest' will be
printed (line 19), else if condition2 fails, then 'C is greatest' will be
printed (line 21).
Code line 24: Printing the statement "Program completed" (line 24).
Output of code:
Program started.
Checking Nested-IF 2
C is greatest
Program completed.
Syntax:
CASE (expression)
WHEN <valuel> THEN action_blockl;
WHEN <value2> THEN action_block2;
WHEN <value3> THEN action_block3;
ELSE action_block_default;
END CASE;
In the above syntax, the expression will return a value that could be of
any type (variable, number, etc.).
Each 'WHEN' clause is treated as an alternatives which have <value>
and <action_block>.
The 'WHEN' clause which matches the value as that of the expression
will be selected, and the corresponding <action_block> will be
executed.
'ELSE' block is optional which hold the <action_block_default> that
needs to be executed when none of the alternatives match the
expression value.
The 'END' marks the end of the CASE statement, and it is a mandatory
part of the CASE.
DECLARE
a NUMBER :=55;
b NUMBER :=5;
arth_operation VARCHAR2(20) :='MULTIPLY’;
BEGIN
dbms_output.put_line(‘Program started.' );
CASE (arth_operation)
WHEN ‘ADD’ THEN dbms_output.put_line(‘Addition of the numbers are: '|| a+b );
WHEN ‘SUBTRACT' THEN dbms_output.put_line(‘Subtraction of the numbers are: '||a-b
);
WHEN ‘MULTIPLY' THEN dbms_output.put_line(‘Multiplication of the numbers are: '||
a*b
);
WHEN ‘DIVIDE' THEN dbms_output.put_line(‘Division of the numbers are:'|| a/b);
ELSE dbms_output.put_line(‘No operation action defined. Invalid operation');
END CASE;
dbms_output.put_line(‘Program completed.' );
END;
/
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '55'.
Code line 3: Declaring the variable 'b' as 'NUMBER' data type and
initializing it with value '5.'
Code line 4: Declaring the variable 'arth_operation' as 'VARCHAR2' data
type of size 20 and initializing it with value 'MULTIPLY'.
Code line 6: Printing the statement "Program started".
Code line 7: CASE checks the value of the expression. In this case, the
value of the variable 'arth_operation' is 'MULTIPLY'. This value will be
treated as a selector for this CASE statement now.
Code line 10: The WHEN clause with value 'MULTIPLY' matches with
the selector value, hence controller will select this action_block and will
print the message 'Multiplication of the numbers are: 275'.
Code line13: Marks the end of the CASE statement.
Code line14: Printing the statement "Program completed".
Code Output:
Program started.
Multiplication of the numbers are: 275
Program completed.
The first WHEN clause that satisfies the condition will be executed, and
the controller will skip the remaining alternatives.
Syntax:
CASE
WHEN <expression1> THEN action_blockl;
WHEN <expression2> THEN action_block2;
WHEN <expression3> THEN action_block3;
ELSE action_block_default;
END CASE;
In the above syntax, each WHEN clause has the separate <expression>
and <action_block>.
The WHEN clause for which the expression returns TRUE will be
executed.
'ELSE' block is optional which hold the <action_block_default> that
needs to be executed when none of the alternatives satisfies.
The 'END' marks the end of the CASE statement and, it is a mandatory
part of CASE.
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '55'.
Code line 3: Declaring the variable 'b' as 'NUMBER' data type and
initializing it with value '5'.
Code line 4: Declaring the variable 'arth_operation' as 'VARCHAR2' data
type of size 20 and initializing it with value 'DIVIDE.'
Code line 6: Printing the statement "Program started".
Code line 7: SEARCHED CASE statement begins. The code from line8 to
line 13 is skipped as their selector value (ADD, SUBTRACT, MULTIPLY)
doesn't match with the value of 'arth_operation'.
Code line 14: The WHEN clause expression "arth_operation = 'DIVIDE'"
satisfied and the expression returns TRUE.
Code line 15: Action_block of the WHEN clause will be executed, and
message 'Division of the numbers are: 11' will be printed.
Code line 17: Marks the end of CASE statement.
Code line 18: Printing the statement "Program completed".
Code Output:
Program started.
Division of the numbers are: 11
Program completed.
In this tutorial, we are going to see the loop concept in PL/SQL and flow of
control in loops. You will learn-
Reusability of code
Reduced code size
Easy flow of control
Reduced Complexity
In the above diagram, the loop condition will be checked, and as long as the
loop condition is satisfied, the execution block will be executed.
In each iteration, the loop counter variable that actually decides the loop
condition should modify to make the control exit from the loop. In some cases,
this loop counter variable is increment/decrement operator for a predefined
count, and in some case, it is a search condition that keeps on executing the
block till it satisfies it.
GOTO
This statement will transfer the control to the labeled statement ("GOTO
<label> ;"). This has the following restrictions
It needs EXIT keyword to be given explicitly in the execution part to exit from
the loop.
LOOP
<execution block starts>
<EXIT condition based on developer criteria>
<execution_block_ends>
END LOOP;
Syntax Explanation:
In the above syntax, key word 'LOOP' marks the beginning of the loop
and 'END LOOP' marks the end of the loop.
The execution block contains all the code that needs to be executed
including the EXIT condition.
The execution part can contain any execution statement.
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '1'.
Code line 4: Printing the statement "Program started".
Code line 5: Keyword 'LOOP' marks the beginning of the loop.
Code line 6: Prints the value of 'a'.
Code line 7: Increments the value of 'a' by +1.
Code line 8: Checks whether the value of 'a' is greater than 5.
Code line 9: Keyword 'END LOOP' marks the end of execution block.
The code from line 6 to line 8 will continue to execute till 'a' reaches the
value 6, as the condition will return TRUE, and the control will EXIT
from the loop.
Code line 10: Printing the statement "Program completed"
Labeling of Loops
In PL/SQL, the loops can be labeled. The label should be enclosed between
"<<" and ">>". The labeling of loops particularly in nested loop codes will
give more readability. The label can be given in EXIT command to exit from
that particular loop. Using label, the control can be made to directly exit the
outer loop of the nested loops from anyplace inside the loops, by giving the
exit command followed by outer loop label.
<<OUTER_LOOP>>
LOOP
<execution_block_starts>
.
<<INNER_LOOP>>
LOOP --inner
<execution_part>
END LOOP;
.
<executi_block_ends>
END LOOP;
Syntax Explanation:
In the above syntax, the out loop has one more loop inside it.
The '<<OUTER_LOOP>>' and '<<INNER_LOOP>>' are the labels of
these loops.
Code Explanation:
Code line 2-3: Declaring the variable 'a' and 'b' as 'NUMBER' data type.
Code line 4: Declaring the variable 'upper_limit' as 'NUMBER' data type
with value '4'
Code line 6: Printing the statement "Program started".
Code line 7: The outer loop has been labeled as "outer_loop"
Code line 9: The value of 'a' is incremented by 1.
Code line 11: Inner loop has been labeled as "inner_loop".
Code line 13: EXIT condition that check whether the value 'a' is higher
than 'upper_limit' value. If not then it will go further, else it exits outer
loop directly.
Code line 14: Printing the value of 'b'.
Code line 15: Increments the value of 'b' by +1.
Code line 16: EXIT condition that checks whether the value of 'b' is
higher than 'a'. If so, then it will exit the control from the inner loop.
In this loop, the lower limit and the higher limit will be specified and as long
as the loop variable is in between this range, the loop will be executed.
In the above syntax, keyword 'FOR' marks beginning of the loop and
'END LOOP' marks the end of the loop.
Loop variable is evaluated every time before executing the execution
part.
The execution block contains all the code that needs to be executed. The
execution part can contain any execution statement.
The loop_variable is declared implicitly during the execution of the
entire loop, and the scope of this loop_variable will be only inside this
loop.
If the loop variable came out of the range, then control will exit from the
loop.
The loop can be made to work in the reverse order by adding the
keyword 'REVERSE' before lower_limit.
BEGIN
dbms Qutput.put linef.Prp.gram started.' );
FOR a IN 1 .. 5
LOOP
dbms_output.put_line(a);
END LOOP:
dbms_output.put_iine('Program completed.');
END;
/
Code Explanation:
Nested Loops
The loop statements can also be nested. The outer and inner loop can be of
different types. In the nested loop, for every one iteration value of the outer
loop, the inner loop will be executed fully.
LOOP -outer
<execution block starts>
LOOP — inner
<execution_part>
END LOOP;
<execution_block_ends>
END LOOP;
Syntax Explanation:
In the above syntax, the outer loop has one more loop inside it.
The loops can be of any types and execution functionality part is same.
DECLARE
b NUMBER;
BEGIN
dbms output put line(‘Program started' );
FOR a IN 1..3
LOOP
b:=1;
WHILE (a>=b)
LOOP
dbms output put line(a);
b:=b+1;
END LOOP;
END LOOP;
dbms_output.put_line('Program completed' );
END;
/
Code Explanation:
It works like an entry-check loop in which execution block will not even be
executed once if the condition is not satisfied, as the exit condition is checking
before execution part. It does not require keyword 'EXIT' explicitly to exit
from the loop since it is validating the condition implicitly each time of the
loop.
In the above syntax, keyword 'WHILE' marks beginning of the loop and
'END LOOP' marks the end of the loop.
EXIT condition is evaluated each time before the execution part is
starting executing.
The execution block contains all the code that needs to be executed.
The execution part can contain any execution statement.
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '1'.
Code line 4: Printing the statement "Program started".
Code line 5: Keyword 'WHILE' marks the beginning of the loop, and it
also checks whether the value of 'a' is greater than 5
Code line 7: Prints the value of 'a'.
Code line 8: Increments the value of 'a' by +1.
Code line 9: Keyword 'END LOOP' marks the end of execution block.
The code from line 7 and line 8 will continue to execute till 'a' reaches
the value 6, as the condition will return TRUE, and the control will EXIT
from the loop.
Procedural Language
A procedural language is a
computer programming language that follows,
in order, a set of commands. Examples of
computer procedural languages
are BASIC, C, FORTRAN, Java, and Pascal.
Procedural Language
A procedural language, as the name implies, relies on predefined and well-organized
procedures, functions or sub-routines in a program’s architecture by specifying all
the steps that the computer must take to reach a desired state or output.
The procedural language segregates a program within variables, functions,
statements and conditional operators. Procedures or functions are implemented on
the data and variables to perform a task. These procedures can be called/invoked
anywhere between the program hierarchy, and by other procedures as well. A
program written in procedural language contains one or more procedures.
Procedural language is one of the most common types of programming languages in use,
with notable languages such as C/C++, Java, ColdFusion and PASCAL
Triggers
Trigger is a statement that a system executes automatically when there is any modification
to the database.
For Example