Sei sulla pagina 1di 58

What is PL/SQL

PL/SQL (Procedural Language for SQL) is Oracle


Corporation's procedural extension for SQL and the Oracle relational database. PL/SQL is
available in Oracle Database (since version 6 - stored PL/SQL
procedures/functions/packages/triggers since version 7)
PL/SQL is Oracle Corporation's procedural extension for SQL and the Oracle relational
database. PL/SQL is available in Oracle Database, Times Ten in-memory database, and IBM DB
2. Oracle Corporation usually extends PL/SQL functionality with each successive release of the
Oracle Database

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.

PL/SQL program unit[edit]


The main feature of SQL (non-procedural) is also a drawback of SQL: one cannot use control
statements (decision-making or iterative control) if only SQL is to be used. PL/SQL is basically a
procedural language, which provides the functionality of decision making, iteration and many
more features like other procedural programming languages. A PL/SQL program unit is one of
the following: PL/SQL anonymous block, procedure, function, package specification, package
body, trigger, type specification, type body, library. Program units are the PL/SQL source code
that is compiled, developed and ultimately executed on the database.

PL/SQL anonymous block[edit]


The basic unit of a PL/SQL source program is the block, which groups together related
declarations and statements. A PL/SQL block is defined by the keywords DECLARE, BEGIN,
EXCEPTION, and END. These keywords divide the block into a declarative part, an executable
part, and an exception-handling part. The declaration section is optional and may be used to
define and initialize constants and variables. If a variable is not initialized then it defaults
to NULL value. The optional exception-handling part is used to handle run time errors. Only the
executable part is required. A block can have a label.
For example:

<<label>> -- this is optional


DECLARE
-- this section is optional
number1 NUMBER(2);
number2 number1%TYPE := 17; -- value default
text1 VARCHAR2(12) := 'Hello world';
text2 DATE := SYSDATE; -- current date and time
BEGIN
-- this section is mandatory, must contain at least one executable
statement
SELECT street_number
INTO number1
FROM address
WHERE name = 'INU';
EXCEPTION
-- this section is optional
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error Code is ' || TO_CHAR(sqlcode));
DBMS_OUTPUT.PUT_LINE('Error Message is ' || sqlerrm);
END;

The symbol := functions as an assignment operator to store a value in a variable.


Blocks can be nested – i.e., because a block is an executable statement, it can appear in another
block wherever an executable statement is allowed. A block can be submitted to an interactive
tool (such as SQL*Plus) or embedded within an Oracle Precompiler or OCI program. The
interactive tool or program runs the block once. The block is not stored in the database, and for
that reason, it is called an anonymous block (even if it has a label).

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.

 This particular section is optional and can be skipped if no declarations


are needed.
 This should be the first section in a PL/SQL block, if present.
 This section starts with the keyword 'DECLARE' for triggers and
anonymous block. For other subprograms, this keyword will not be
present. Instead, the part after the subprogram name definition marks
the declaration section.
 This section should always be followed by execution section.

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'.

The Keyword 'END' marks the end of PL/SQL block.

PL/SQL Block Syntax


Below is the syntax of the PL/SQL block structure.
DECLARE --optional
<declarations>

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.

Types of PL/SQL block


PL/SQL blocks are of mainly two types.

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.

Below are few more characteristics of Anonymous blocks.

 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.

Below are few more characteristics of Named blocks.

 These blocks can be called from other blocks.


 The block structure is same as an anonymous block, except it will never
start with the keyword 'DECLARE'. Instead, it will start with the
keyword 'CREATE' which instruct the compiler to create it as a database
object.
 These blocks can be nested within other blocks. It can also contain
nested blocks.
 Named blocks are basically of two types:

1. Procedure
2. Function

We will learn more about these named blocks in "Procedure" and "Function"
topics in later tutorial.

PL/SQL First Program: Hello World Example

What is SQL* Plus?


SQL* Plus is an interactive and batch query tool that is installed with every
Oracle installation.

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

How to write a simple program using PL/SQL

BEGIN
2 dbms_output.put_line (‘Hello World..');
3 END:
4 /

Declaring and usage of variables in the program

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.

Comment can be used in the program to increase the readability of the


program. In PL/SQL codes can be commented in two ways.

 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;
/

What is PL/SQL Datatypes?

Following is the diagram of different Data Types in PL/SQL


In this tutorial, you will learn-

 CHARACTER Data Type


 NUMBER Data Type
 BOOLEAN Data Type
 DATE Data Type
 LOB Data Type

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
Data Type Description Syntax

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:

 Oracle would be blank-padded the  The first declaration


variable if the variable didn't statement declared the
occupy the entire size that has variable 'grade' of CHAR
been declared for it, Hence Oracle data type with the maxim
will allocate the memory for size of 1 byte (default va
declared size even if the variable  The second declaration
didn't occupy it fully. statement declared the
 The size restriction for this data variable 'manager' of CH
type is 1-2000 bytes. data type with the maxim
 CHAR data type is more size of 10 and assigned th
appropriate to use where ever value 'guru99' which is o
fixed the size of data will be bytes. Oracle will allocate
handled. the memory of 10 bytes
rather than 6 bytes in thi
case.

VARCHAR2 This data type stores the string, but the manager VARCHAR2(10) := ‘guru99';
length of the string is not fixed. Syntax Explanation:

 The size restriction for this data  The above declaration


type is 1-4000 bytes for table statement declared the
column size and 1-32767 bytes for variable 'manager' of
variables. VARCHAR2 data type wit
 The size is defined for each the maximum size of 10 a
variable at the time of variable assigned the value 'guru9
declaration. which is of 6 bytes. Oracl
 But Oracle will allocate memory will allocate memory of o
only after the variable is defined, 6 bytes in this case.
i.e., Oracle will consider only the
actual length of the string that is
stored in a variable for memory
allocation rather than the size that
has been given for a variable in the
declaration part.
 It is always good to use VARCHAR2
instead of CHAR data type to
optimize the memory usage.

VARCHAR This is synonymous with the VARCHAR2 manager VARCHAR(10) := ‘guru99';


data type. Syntax Explanation:

 It is always a good practice to use  The above declaration


VARCHAR2 instead of VARCHAR to statement declared the
avoid behavioral changes. variable 'manager' of
VARCHAR data type with
maximum size of 10 and
assigned the value 'guru9
which is of 6 bytes. Oracl
will allocate memory of o
6 bytes in this case. (Sim
to VARCHAR2)

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.

 The above declaration


statement declares the
 This character set can be defined variable 'native' of NCHA
for the session using data type with the maxim
NLS_PARAMETERS. size of 10.
 The character set can be either  The length of this variabl
UTF16 or UTF8. depends upon the (numb
 The size restriction is 1-2000 of lengths) per byte as
bytes. defined in the character s

NVARCHAR2 This data type is same as VARCHAR2 Native var NVARCHAR2(10):='guru99


data type, but the character set will be of Syntax Explanation:
the national character set.

 This character set can be defined


for the session using  The above declaration
NLS_PARAMETERS. statement declares the
variable 'Native_var' of
 The character set can be either NVARCHAR2 data type w
UTF16 or UTF8. the maximum size of 10.
 The size restriction is 1-4000
bytes.

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:

 These are mainly used in the data


dictionary.
 LONG data type is used to store  The above declaration
character set data, while LONG statement declares the
RAW is used to store data in binary variable 'Large_text' of L
format. data type and 'Large_raw
 LONG RAW data type accepts LONG RAW data type.
media objects, images, etc.
whereas LONG works only on data Note: Using LONG data type is n
that can be stored using character recommended by Oracle. Instea
set. LOB data type should be prefer

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 this information. Values need not enclose within
quotes while assigning for this data type.

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:

 In the above, variable 'Var1' is declared as BOOLEAN data type. The


output of the code will be either true or false based on the condition set.

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:

 In the above, variable 'newyear' is declared as DATE data type and


assigned the value of Jan 1st, 2015 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.

LOB Data Type:


This data type is mainly used to store and manipulate large blocks of
unstructured data's like images, multimedia files, etc. Oracle prefers LOB
instead of the a LONG data type as it is more flexible than the LONG data type.
The below are the few main advantage of LOB over LONG data type.

 The number of column in a table with LONG data type is limited to 1,


whereas a table has no restriction on a number of columns with LOB
data type.
 The data interface tool accepts LOB data type of the table during data
replication, but it omits LONG column of the table. These LONG columns
need to be replicated manually.
 The size of the LONG column is 2GB, whereas LOB can store up to 128
TB.
 Oracle is constantly improvising the LOB data type in each of their
releases according to the modern requirement, whereas LONG data
type is constant and not getting many updates.

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

Data Description Syntax


Type

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

images, etc. 'Binary_data' is declared


a BLOB.

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

etc. that cannot be put into a character string. 'Charac_data' is declare


The maximum size of these data types is 128 CLOB data type.
TB.

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.

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.

In this tutorial, you will learn-

 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

Naming Conventions of Identifiers


In a complex program, sometimes we may have to include many identifiers.
These identifiers include variables, cursors, etc. So to avoid confusion and to
increase the readability of such program we need to follow certain naming
conventions.

Following are the commonly used naming conventions in PL/SQL.

 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

Below are some of the examples of proper naming conventions

 Lv_name – local level variable of varchar/char datatype


 Pc_num – parameter level cursor identifier
 Gn_user_id – Global level variable of numerical data type
 Example1: In this example, we are going to learn how to declare the
variable and how to assign the value to them. We are going to print
'GURU99' in the following program by using the variables.

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).

In the collection, each element is identified by a term called "subscript." Each


item in the collection is assigned with a unique subscript. The data in that
collection can be manipulated or fetched by referring to that unique subscript.

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.

In this tutorial, you will learn-

 What is Collection?
 Varrays
 Nested Tables
 Index-by-table
 Constructor and Initialization Concept in Collections
 Collection Methods

Collections are classified based on the structure, subscript, and storage as


shown below.

 Index-by-tables (also known as Associative Array)


 Nested tables
 Varrays

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.

 Upper limit size is fixed


 Populated sequentially starting with the subscript '1'
 This collection type is always dense, i.e. we cannot delete any array
elements. Varray can be deleted as a whole, or it can be trimmed from
the end.
 Since it always is dense in nature, it has very less flexibility.
 It is more appropriate to use when the array size is known and to
perform similar activities on all the array elements.
 The subscript and sequence always remain stable, i.e. the subscript and
count of the collection is always same.
 They need to be initialized before using them in programs. Any
operation (except EXISTS operation) on an 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 Varray (dense)
diagrammatically.

Subscript 1 2 3 4 5 6 7

Value Xyz Dfv Sde Cxs Vbc Nhu Qwe

Syntax for VARRAY:

TYPE <type_name> IS VARRAY (<SIZE>) OF <DATA_TYPE>;

 In the above syntax, type_name is declared as VARRAY of the type


'DATA_TYPE' for the given size limit. The data type can be either simple
or complex type.

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

Value (dense) Xyz Dfv Sde Cxs Vbc Nhu Qwe

Value(sparse) Qwe Asd Afg Asd Wer

Syntax for Nested Table:

TYPE <tvpe name> IS TABLE OF <DATA TYPE>;

 In the above syntax, type_name is declared as Nested table collection of


the type 'DATA_TYPE'. The data type can be either simple or complex
type.

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 subscript can of integer or strings. At the time of creating the


collection, the subscript type should be mentioned.
 These collections are not stored sequentially.
 They are always sparse in nature.
 The array size is not fixed.
 They cannot be stored in the database column. They shall be created
and used in any program in that particular session.
 They give more flexibility in terms of maintaining subscript.
 The subscripts can be of negative subscript sequence also.
 They are more appropriate to use for relatively smaller collective values
in which the collection can be initialized and used within the same
subprograms.
 They need not be initialized before start using them.
 It cannot be created as a database object. It can only be created inside
the subprogram, which can be used only in that subprogram.
 BULK COLLECT cannot be used in this collection type as the subscript
should be given explicitly for each record in the collection.

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.

Subscript (varchar) FIRST SECOND THIRD FOURTH FIFTH SIXTH SEVENTH

Value(sparse) Qwe Asd Afg Asd Wer

Syntax for Index-by-Table

TYPE <type_name> IS TABLE OF <DATA_TYPE> INDEX BY VARCHAR2 (10);

 In the above syntax, type_name is declared as an index-by-table


collection of the type 'DATA_TYPE'. The data type can be either simple
or complex type. The subsciprt/index variable is given as VARCHAR2
type with maximum size as 10.

Constructor and Initialization Concept in Collections


Constructors are the in-built function provided by the oracle that has the same
name as of the object or collections. They are executed first whenever object
or collections are getting referred for the first time in a session. Below are the
important details of constructor in collection context:

 For collections, these constructors should be called explicitly to


initialize it.
 Both Varray and Nested tables need to be initialized through these
constructors before getting referred into the program.
 Constructor implicitly extends the memory allocation for a collection
(except Varray), hence constructor can also assign the variables to the
collections.
 Assigning values to the collection through constructors will never make
the collection 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.

Method Description SYNTAX

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

PRIOR Returns precedes index variable in a collection of the <collection_name>.PRIOR(n)


(n) nth element. If there is no precedes index value NULL is
returned

NEXT (n) Returns succeeds index variable in a collection of the <collection_name>.NEXT(n)


nth element. If there is no succeeds index value NULL is
returned

EXTEND Extends one element in a collection at the end <collection_name>.EXTEND

EXTEND Extends n elements at the end of a collection <collection_name>.EXTEND(n)


(n)

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)

Example1: Record Type at Subprogram level

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:

SELECT emp no,emp_name,manager,salary BULK COLLECT INTO guru99_emp_rec


FROM emp;
dbms_output.put_line (‘Employee Detail');
FOR i IN guru99_emp_rec.FIRST..guru99_emp_rec.LAST
LOOP
dbms_output.put_line (‘Employee Number: '||guru99_emp_rec(i).emp_no);
dbms_output.put_line (‘Employee Name: '||guru99_emp_rec(i).emp_name);
dbms_output.put_line (‘Employee Salary:'|| guru99_emp_rec(i).salary);
dbms_output.put_line(‘Employee Manager Number:'||guru99_emp_rec(i).manager);
dbms_output.put_line('--------------------------------');
END LOOP;
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: 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
----------------------------------------------

What is Record Type?


A Record type is a complex data type which allows the programmer to create a
new data type with the desired column structure.

 It groups one or more column to form a new data type


 These columns will have its own name and data type
 A Record type can accept the data
o As a single record that consists of many columns OR
o It can accept the value for one particular column of a record
 Record type simply means a new data type. Once the record type is
created, it will be stored as a new data type in the database and the
same shall be used to declare a variable in programs.
 It will use the keyword 'TYPE' to instruct the compiler that it is creating
the new data type.
 It can be created at "database level" which can be stored as database
objects, used all-over the database or it can be created at the
"subprogram levels", which is visible only inside the subprograms.
 The database level record type can also be declared for the table
columns so that single column can hold the complex data.
 The data in these data type can be accessed by referring to their
variable_name followed by period operator (.) followed by
column_name i.e. '<record_type_variable_name>.<column_name>'

Syntax for declaration at the database level:

CREATE TYPE <type_name_db> IS RECORD


(
<column 1> <datatype>,
);

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.

This is given as an individual statement and not inside any block.

Syntax for declaration at subprogram level:


DECLARE
TYPE <type_name> IS RECORD
(
<columnl> <datatype>,
);
BEGIN
<execution_section>;
END;

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.

Example 1: RECORD Type as Database Object

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)

CREATE TYPE emp_det IS RECORD


(
EMP_NO NUMBER,
EMP_NAME VARCHAR2(150),
MANAGER NUMBER,
SALARY NUMBER
);
/
Output:
Type created

Code Explanation:

 The above code will create type emp_det as a database object.


 It will have 4 column emp_no, emp_name, manager and salary as
defined.
 Now 'emp_det' is a similar to other data type (like NUMBER,
VARCHAR@, etc.) And it is visible in the entire database. Hence this can
be used in the entire database to declare the variable of this type.

Output:

Created the type 'emp_det' as record type at the database level.

Example 2: Record Type at Subprogram level- Column level access

In this example, we are going to see how to create a record type at


subprogram level and how to populate and fetch the values from it by column
level.

We are going to create 'emp_det' record_type at subprogram level, and we are


going to use the same to populate and to display data from it.

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

In this example, we are going to see how to create a record type at


subprogram level and how to populate it as a row level. We are going to create
'emp_det' record_type at subprogram level, and we are going to use the same
to populate and to display data from it.

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.

Oracle PL/SQL IF THEN ELSE Statement: ELSIF, NESTED-IF

What are Decision-Making Statements?


Decision making statements are those who will decide the flow-control
of SQL statements based on the conditions. It gives the programmer a better
control of preventing a particular code from executing (diagram 1) or
choosing a desired code based on the condition (diagram 2). Below is the
pictorial representation of the "Decision Making Statement".
Decision Making Statement Diagram

Types of Decision Making Statements:

Oracle provides the following types of decision making statements.

 IF-THEN
 IF-THEN-ELSE
 IF-THEN-ELSIF
 NESTED-IF
 CASE
 SEARCHED CASE

In this tutorial, you will learn-

 Introduction to Decision Making Statements


 IF-THEN Statement
 IF-THEN-ELSE Statement
 IF-THEN-ELSIF Statement
 NESTED-IF Statement

IF-THEN Statement
The IF-THEN statement is mainly used to execute a particular section of codes
only when the condition is satisfied.

The condition should yield Boolean (True/False). It is a basic conditional


statement which will allow the ORACLE to execute/skip a particular piece of
code based on the pre-defined conditions.

Syntax for IF THEN Statements:

IF <condition: returns Boolean>


THEN
-executed only if the condition returns TRUE
<action_block>
END if;

 In the above syntax, keyword 'IF' will be followed by a condition which


evaluates to 'TRUE'/'FALSE'.
 The control will execute the <action_block> only if the condition
returns <TRUE>.
 In the case of condition evaluates to <FALSE> then, SQL will skip the
<action_block>, and it will start executing the code next to 'END IF'
block.

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.

Example 2: In this example, we are going to print a message if a given alphabet


is present in English vowels (A, E, I, O, U).

To print a message when the given character is Vowel, we execute the


following code.

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.

Syntax for IF-THEN-ELSE Statements:

IF <condition: returns Boolean>


THEN
-executed only if the condition returns TRUE
<action_blockl>
ELSE
-execute if the condition failed (returns FALSE)
<action_block2>
END if;

 In the above syntax, keyword 'IF' will be followed by a condition which


evaluates to 'TRUE'/'FALSE'.
 The control will execute the <action_block1> only if the condition
returns <TRUE>.
 In case of condition evaluates to <FALSE> then, SQL will execute
<action_block2>.
 In any case, one of the two action blocks will be executed.

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: ELSE block is optional in this conditional statement. If there is no ELSE


block, and none of the condition satisfied, then the controller will skip all the
action block and start executing the remaining part of the code.

Syntax for IF-THEN-ELSIF Statements:

IF <conditionl: returns Boolean>


THEN
-executed only if the condition returns TRUE <
action_blockl>
ELSIF <condition2 returns Boolean> <
action_block2>
ELSIF <condition3:returns Boolean> <
action_block3>
ELSE —optional
<action_block_else>
END if;
 In the above syntax, the control will execute the <action_block1> only
if the condition1 returns <TRUE>.
 If condition1 is not satisfied, then the controller will check for
condition2.
 The controller will exit from the IF-statement in the following two
cases.
o When the controller found any condition that returns <TRUE>.
In this case, the corresponding action_block will be executed and
the controller will exit this IF-statement block and will start
executing the remaining code.
o When none of the conditions satisfied, the then controller will
execute ELSE block if present, then will exit from the IF-
statement.

Note: Whenever condition evaluates to 'NULL', then SQL will treat 'NULL' as
'FALSE'.

Example 1: Without ELSE block

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.

Example 2: With ELSE block

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>.

Here we are going to see an example of Nested If –

Example of Nested- If Statement: Greatest of three number

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.

Oracle PL/SQL: CASE Statement with Examples

What is CASE Statement?


A CASE statement is similar to IF-THEN-ELSIF statement that selects one
alternative based on the condition from the available options.

 CASE statement uses "selector" rather than a Boolean expression to


choose the sequence.
 The value of the expression in the CASE statement will be treated as a
selector.
 The expression could be of any type (arithmetic, variables, etc.)
 Each alternative is assigned with a certain pre-defined value (selector),
and the alternative with selector value that matches the conditional
expression value will get executed.
 Unlike IF-THEN-ELSIF, the CASE statement can also be used in SQL
statements.
 ELSE block in CASE statement holds the sequence that needs to be
executed when none of the alternatives got selected.

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.

Example 1: Arithmetic Calculation using Case

In this example, we are going to do arithmetic calculation between two


numbers 55 and 5.

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.

SEARCHED CASE Statement


The SEARCHED CASE statement is similar to the CASE statement, rather than
using the selector to select the alternative, SEARCHED CASE will directly have
the expression defined in the WHEN clause.

 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.

Example 1: Arithmetic Calculation using Searched Case

In this example, we are going to do arithmetic calculation between two


numbers 55 and 5.

DECLARE a NUMBER :=55;


b NUMBER :=5;
arth_operation VARCHAR2(20) :='DIVIDE';
BEGIN
dbms_output.put_line(‘Program started.' );
CASE
WHEN arth_operation = 'ADD'
THEN dbms_output.put_line(‘Addition of the numbers are: '||a+b );
WHEN arth_operation = ‘SUBTRACT'
THEN dbms_output.put_line(‘Subtraction of the numbers are: '|| a-b);
WHEN arth_operation = ‘MULTIPLY’
THEN dbms_output.put_line(‘Multiplication of the numbers are: '|| a*b );
WHEN arth_operation = ’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 '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.

What are Loops?


Loops allows a certain part of the code in a program to get executed for the
desired number of times.

In this tutorial, we are going to see the loop concept in PL/SQL and flow of
control in loops. You will learn-

 Introduction to Loops Concept


 Loop Control Statements
 Types of Loop in PL/SQL
 Basic Loop Statement
 Labeling of Loops

Introduction to Loops Concept


Loops concept provides the following advantage in coding.

 Reusability of code
 Reduced code size
 Easy flow of control
 Reduced Complexity

The below diagram shows the looping concept in a pictorial manner

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.

Loop Control Statements


Before learning the loops concept, it is mandatory to learn of loop control
statements. Loop control statements are those that actually control the flow of
execution inside the loop. Below is the detailed description about the loop
control statements.
CONTINUE
This keyword sends an instruction to the PL/SQL engine that whenever
PL/SQL engine encounters this keyword inside the loop, then it will skip the
remaining code in the execution block of the code, and next iteration will start
immediately. This will be mainly used if the code inside the loop wants to be
skipped for certain iteration values.

EXIT / EXIT WHEN


This keyword sends an instruction to the PL/SQL engine that whenever
PL/SQL engine encounters this keyword, then it will immediately exit from
the current loop. If the PL/SQL engine encounters the EXIT in a nested loop,
then it will come out of the loop in which it has been defined, i.e. in a nested
loops, giving EXIT in the inner loop will only exit the control from inner loop
but not from the outer loop. 'EXIT WHEN' is followed by an expression which
gives a Boolean result. If the result is TRUE, then the control will EXIT.

GOTO
This statement will transfer the control to the labeled statement ("GOTO
<label> ;"). This has the following restrictions

 Transfer of control can be done only within the subprograms.


 Transfer of control cannot be done from exception handling part to the
execution part

Usage of this statement is not recommended unless there are no other


alternatives, as the code-control traceability will be very difficult in the
program due to the transfer of control from one part to another part.

Types of Loop in PL/SQL


PL/SQL provides following three types of loops

 Basic loop statement


 For loop statement
 While loop statement

Basic Loop Statement


This loop statement is the simplest loop structure in PL/SQL. The execution
block starts with keyword 'LOOP' and ends with the keyword 'END LOOP'.
The exit condition should be given inside this execution block so that control
exit from the loop.

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.

Note: Basic loop statement with no EXIT keyword will be an INFINITE-LOOP


that will never stop.

Example 1: In this example, we are going to print number from 1 to 5 using


basic loop statement. For that, we will execute the following code.
DECLARE
a NUMBER:=1;
BEGIN
dbms_output.put_line('Program started.');
LOOP
dbms_output.put_line(a);
a:=a+1;
EXIT WHEN a>5;
END LOOP;
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 '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.

Example 1: In this example, we are going to print number starting from 1


using Basic loop statement. Each number will be printed as many times as its
value. The upper limit of the series is fixed at the program declaration part.
Let us learn how we can use the label concept to achieve this. For that, we will
execute the following code
DECLARE
a NUMBER:=0;
b NUMBER;
upper-limit NUMBER :=4;
BEGIN
dbms_output.put_line(‘Program started.' );
«outerloop»
LOOP
a:=a+1;
b:=l;
«inner loop»
LOOP
EXIT outer_loop WHEN a > upper_limit;
dbms_output.put_line(a);
b:=b+l;
EXIT inner_loop WHEN b>a;
END LOOP;
END LOOP;
dbms_output.put_line('Program completed.');
END;
/

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.

 Code line 14: Printing the statement "Program completed"

What is For Loop?


"FOR LOOP" statement is best suitable when you want to execute a code for a
known number of times rather than based on some other conditions.

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.

The loop variable is self-incremental, so no explicit increment operation is


needed in this loop. The loop variable need not to be declared, as it is declared
implicitly.

FOR <loop_variable> in <lower_limit> .. <higher_limit>


LOOP
<execution block starts>
.
.
.
<execution_block_ends>
END LOOP;
Syntax Explanation:

 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.

Example 1: In this example, we are going to print number from 1 to 5 using


FOR loop statement. For that, we will execute the following code.

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:

 Code line 2: Printing the statement "Program started".


 Code line 3: Keyword 'FOR' marks the beginning of the loop and
loop_variable 'a' is declared. It now will have the value starting from 1
to 5
 Code line 5: Prints the value of 'a'.
 Code line 6: Keyword 'END LOOP' marks the end of execution block.
 The code from line 5 will continue to execute till 'a' reaches the value 6,
as the condition will fail, and the control will EXIT from the loop.

 Code line 7: Printing the statement "Program completed"

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.

Example 1: In this example, we are going to print number from 1 to 3 using


FOR loop statement. Each number will be printed as many times as its value.
For that, we will execute the following code.

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:

 Code line 2: Declaring the variable 'b' as 'NUMBER' data type.


 Code line 4: Printing the statement "Program started".
 Code line 5: Keyword 'FOR' marks the beginning of the loop and
loop_variable 'a' is declared. It now will have the value starting from 1
to 3
 Code line 7: Resetting the value of 'b' to '1' each time.
 Code line 8: Inner while loop checks for the condition a>=b.
 Code line 10: Prints the value of 'a' as long as the above condition is
satisfied.

 Code line 14: Printing the statement "Program completed"

What is While Loop?


WHILE loop statement works similar to the Basic loop statement except the
EXIT condition is at the very beginning of the loop.

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.

WHILE <EXIT condition>


LOOP
<execution block starts>
.
.
.
<execution_block_ends>
END LOOP;
Syntax Explanation:

 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.

Example 1: In this example, we are going to print number from 1 to 4 using


WHILE loop statement. For that, we will execute the following code.

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.

 Code line 10: Printing the statement "Program completed"


PRAGMA instructions

A pragma is a special instruction to the compiler. Also called a pseudo instruction,


the pragma doesn't change the meaning of a program. It simply passes
information to the compiler. It is very similar, in fact, to the tuning hints you can
embed in a SQL statement inside a block comment.
docstore.mik.ua/orelly/oracle/prog2/ch02_06.htm

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 languages are some of the


common types of programming languages
used by script and software programmers.
They make use of functions, conditional
statements, and variables to create
programs that allow a computer to
calculate and display a desired output.

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

1. AFTER INSERT activated after data is inserted into the table.


2. AFTER UPDATE: activated after data in the table is modified.
3. AFTER DELETE: activated after data is deleted/removed from the table.
4. BEFORE INSERT: activated before data is inserted into the table.
5. BEFORE UPDATE: activated before data in the table is modified.
6. BEFORE DELETE: activated before data is deleted/removed from the table

Potrebbero piacerti anche