Database Chapter 1
Database Chapter 1
Introduction to PL/SQL
1
© SQL Star International Ltd.
Objectives
2
© SQL Star International Ltd.
Introducing PL/SQL
In the journey so far, you have learnt about the Structured Query Language (SQL).
The Oracle software provides a language, Procedural Language/SQL (PL/SQL), which
is an extension of SQL.
PL/SQL implements modularity in the codes you write. It allows you to perform
iterations and handle errors. Features like data hiding and error handling make
PL/SQL a state-of-the-art language for databases.
PL/SQL also allows data manipulation and SQL query statements to be included
within procedural units of code. This makes PL/SQL a powerful transaction processing
mechanism.
• New employees or existing employees who are handed over someone else’s
work, would have a problem understanding the process followed by
the employee vis-à-vis the organization
3
© SQL Star International Ltd.
Integration
Oracle server, through stored procedures and functions, database triggers and
packages
Oracle development tools, through Oracle Developer component triggers
PL/SQL supports the use of SQL datatypes. With direct access provided by SQL,
these shared datatypes integrate PL/SQL with the Oracle server data dictionary.
Hence, PL/SQL successfully bridges the gap between access to database technology
and the need for procedural language capabilities.
Most applications such as Oracle Forms, Oracle Reports and Oracle Graphics, use
shared libraries (that hold code), which can be accessed locally or remotely. To
execute these stored codes, the Oracle tools have their own PL/SQL engine
(independent of the engine present in the Oracle server). The engine first filters out
the SQL statements to send them individually to the SQL statement executor in the
Oracle server. It then processes the remaining procedural statements in the
procedural statement executor in the PL/SQL engine. The procedural statement
executor processes data, which is already inside the client environment and not in
the database. This reduces the workload on the Oracle server and also the amount of
memory required.
PL/SQL also operates with Oracle development tools, thereby adding procedural
processing power to these tools and enhancing performance.
4
© SQL Star International Ltd.
Modularized Program Development
PL/SQL programs are made up of one or more blocks. These blocks may be
individual ones or may be nested within another. That is, a block may represent a
small part of another block, which may in turn be part of a whole unit of code. The
units (procedures, functions or anonymous blocks) making up a PL/SQL program are
called logical blocks.
Portability
PL/SQL is portable. That means, PL/SQL programs can be run wherever the Oracle
server exists. There is no need to tailor them to suit each new environment. This is
achieved because PL/SQL is native to the Oracle server, and therefore can be moved
to any environment (operating system or platform) that supports the Oracle server.
PL/SQL code can also be moved between the Oracle server and Oracle Developer
applications by writing programs and creating libraries in different environments.
5
© SQL Star International Ltd.
Variable Declaration
Handling Errors
PL/SQL implements error handling functionality by:
Block Types
Logical blocks are the basic units of code that make up a PL/SQL program. The two
kinds of PL/SQL blocks are:
Anonymous blocks
Named blocks or Subprograms
Anonymous Blocks
Anonymous blocks are declared at that point in an application from where they are
to be executed and are passed to the PL/SQL engine for execution at runtime. These
blocks are unnamed blocks. They can be embedded in the iSQL*Plus environment.
An application trigger consists of these blocks.
Subprograms
Unlike anonymous blocks, named blocks or subprograms are given a name. These
blocks can be invoked for execution and they can also accept parameters.
6
© SQL Star International Ltd.
Subprograms can be declared as Procedures or Functions. You declare a subprogram
as a Procedure to perform an action, and you declare a subprogram as a Function to
compute a value. Subprograms can be written and stored either at the server side or
at the client side.
Constructs
There are various PL/SQL program constructs available that use the basic PL/SQL
block. The availability of program constructs depends on the environment in which
they are executed.
7
© SQL Star International Ltd.
PL/SQL Block Structure
To write a PL/SQL block, you need to know the different parts of a PL/SQL block and
what each part should hold. The structure of all PL/SQL blocks is the same. The only
difference is that, if it is an anonymous block it is not given a name.
Declarative section
Executable section
Exception handling section
The declarative section is where the variables and constants used in the body of the
block are declared. Any cursors or user-defined error handlers that are used in the
body are declared here. This section is optional.
The executable section holds the set of statements or the logic of the tasks that are
to be performed. You can include SQL statements to make changes to the database
and PL/SQL statements to manipulate data in the block. The statements in this block
are enclosed within the keywords BEGIN and END. This section is mandatory.
The last section of a block is the exception section. Here a set of statements is
written to handle any errors that might occur when the statements in the executable
section are being executed. This section is optional .
8
© SQL Star International Ltd.
The diagramatic expression of PL/SQL block structure is given below.
DECLARE
<variable name> datatype(size);
BEGIN
SQL statements;
PL/SQL statements;
EXCEPTION
WHEN <exception name> THEN
…
END;
/
Some points that will help you write a block:
9
© SQL Star International Ltd.
Identifiers are used to name PL/SQL program constructs such as Constants,
Variables and Exceptions. The following points need to be kept in mind while
using identifiers:
• Do not give the same name for the identifiers as the name of columns
in a table used in the block. If so, then the Oracle server assumes that
the table column is being referred.
• Identifiers should not be reserved words except when they are used
within double quotes, for instance “INSERT”.
10
© SQL Star International Ltd.
Literals are of two types:
Use a semicolon (;) at the end of all SQL and PL/SQL control statements and
the
END keyword.
Do not use semicolons after the keywords DECLARE, BEGIN and EXCEPTION.
Increase the readability of the block by writing the keywords in uppercase.
Use a slash (/) to terminate a PL/SQL block on a line by itself.
SET SERVEROUTPUT ON
BEGIN
--original code
11
© SQL Star International Ltd.
END;
/
Operators in PL/SQL
The following operators are supported in PL/SQL:
Arithmetic
Logical
Relational or Comparison
Concatenation
Exponentiation [Represented by (**)]
These include:
Single-row number and character functions
Datatype conversion functions
Date functions
Timestamp functions
GREATEST and LEAST functions
DECODE
Group functions like AVG, MIN, MAX, COUNT, SUM, STDDEV and
VARIANCE. These functions work only on a group of rows in a table and
hence, they can be used only with the SQL statements in a PL/SQL block.
Variables
A variable are named memory locations used to store data temporarily. The data
stored in variables is used in the blocks and then processed. When the processing is
completed, the data held in the variables may be written to the database or simply
erased in case of session wide variables.
12
© SQL Star International Ltd.
When variables are declared using %TYPE and %ROWTYPE (more information is
provided later in the chapter), you are infact basing the variable declaration on the
column definition of a table. In this case, if the column definition changes, then the
variable declarations also changes accordingly. This helps in data independence,
reduces maintenance cost and allows the program to adjust to the new business
logic.
Types of Variables
Variables are of two types. They are:
PL/SQL variables
Non-PL/SQL variables
PL/SQL Variables
PL/SQL variables have a data type that specifies a storage format, constraints and
also valid range of values.
The data types used to declare PL/SQL variables are:
Scalar data types are those that correspond to database column types. These
data types hold only a single value. The base scalar data types include:
CHAR
VARCHAR2
LONG
LONG RAW
NUMBER
BINARY_INTEGER
PLS_INTEGER
BINARY_FLOAT
BINARY_DOUBLE
BOOLEAN
DATE
TIMESTAMP
TIMESTAMP WITH TIMEZONE
TIMESTAMP WITH LOCAL TIMEZONE
INTERVAL YEAR TO MONTH
INTERVAL DAY TO SECOND
Binary_Float and Binary_Double are the two new Datatypes introduced in
Oracle10g.They represent floating point numbers in IEEE 754 format (Institute of
13
© SQL Star International Ltd.
Electrical and Electronic Engineers) and require 5 byte and 9 bytes to store the
values respectively. IEEE format s supported by most of the computer system
operating through native processor instructions thereby helping us to carry out
complex computations using floating point data.
Composite data types are those that are defined by users. They enable you to
manipulate groups of data in PL/SQL blocks
Reference data types are those that hold values pointing to other objects.
These are also known as pointers.
LOB (large object) data types: are those that hold values, which specify the
location of large objects such as graphic images. These values are known as locators.
Large objects are stored in the same database as the table but not within the table.
LOB data type allows you to store unstructured data of a maximum of 8-128
terabytes. This data could be a movie clip or a graphic image or a sound wave form.
LOBs are further classified into:
Where,
CONSTANT specifies a constraint that the value of the variable cannot change.
Constant variables must be initialized. While declaring a variable as a constant, the
CONSTANT keyword must precede the datatype specification.
DATATYPE specifies the type of data the variable can hold. It could be scalar,
composite, reference or LOB datatype.
NOT NULL specifies a constraint that the variable must contain a value. Therefore,
NOT NULL variables must be initialized.
By default, all variables are initialized to NULL. To prevent null values, variables are
initialized using the DEFAULT keyword.
14
© SQL Star International Ltd.
The following code snippet shows how PL/SQL variables are declared in the
declarative section of a block:
DECLARE
FirstName CHAR(20);
BranchID CHAR(7) NOT NULL: = ‘09RANNJ’;
FeeAmt CONSTANT NUMBER(2): = 15;
CatgName CHAR(15) DEFAULT ‘Fiction’;
% TYPE Attribute
If you need to store a database column value in a variable or write a value from a
variable to a database column, then the data type of the variable needs to be the
same as that of the database column. You can use the %TYPE attribute to declare a
variable to be of the same data type as that of a previously declared variable or
database column.
Incorrect variable data types generate PL/SQL errors during execution. When you
want to declare a variable using a table attribute instead of the datatype the syntax
is
<variable_name> table.columnname%TYPE
For example, in case you want to declare a variable that will store the address of a
library member, you will write in the following syntax:
DECLARE
Address VARCHAR2(45);
But, the above declaration will result in an error when an attempt is made to
populate the variable with address details of members from the database table. This
is because there is a mismatch in type specification of the variable. The datatype
width of the vAddress column in table Member is 50, but you have declared it as
45. To overcome this, declare the variable using %TYPE attribute as follows:
DECLARE
Address Member.vAddress%TYPE;
This statement declares a variable whose datatype and width is based on the
vAddress column.
If you want to declare a variable of the same type as a previously declared variable
then the syntax is
<variable_name> variable_name%TYPE
15
© SQL Star International Ltd.
Datatype and Variable size is determined when the block is compiled. So even if
there is a change in the database column datatype the code manages the changed
datatype information.
DECLARE
cons_nfine NUMBER(3):=50;
cons_extra_fine VARCHAR2(20):=’5';
tot_fine Transaction.nfine%TYPE;
BEGIN
tot_fine:= cons_nfine+cons_extra_fine;
DBMS_OUTPUT.PUT_LINE(‘The total fine payable is
Rs.‘||tot_fine);
END;
/
16
© SQL Star International Ltd.
To perform explicit conversion, following built in functions can be used.
to_char()
to_number()
to_date()
to_Binary_float()
to_Binary_double()
DECLARE
v_Date date:= to_Date( ‘April 04 2007’,’Month dd YYYY’);
BEGIN
DBMS_OUTPUT.PUT_LINE(‘You have entered ‘ ||v_Date ||’ as
input’);
END;
/
DECLARE
l_binary_float BINARY_FLOAT;
l_binary_double BINARY_DOUBLE;
BEGIN
l_binary_float := 2.1f;
l_binary_double := 2.00001d;
DBMS_OUTPUT.PUT_LINE(l_binary_double);
DBMS_OUTPUT.PUT_LINE(l_binary_float);
l_binary_float := TO_BINARY_FLOAT(2.1);
l_binary_double := TO_BINARY_DOUBLE(2.00001);
DBMS_OUTPUT.PUT_LINE(l_binary_double);
DBMS_OUTPUT.PUT_LINE(l_binary_float);
END;
/
17
© SQL Star International Ltd.
Non-PL/SQL Variables
Since PL/SQL has neither input nor output capabilities, it relies on the environment in
which it is executed in order to pass values into and out of a PL/SQL block.
Substitution variables
Host variables
Substitution variables are those that you can use to pass values to a PL/SQL block at
runtime. To reference a substitution variable in a block, prefix it with an ampersand
(&). Before the block is executed the values for the variables are substituted with the
values passed.
Hence, you cannot input different values for the substitution variables using a loop.
The substitution variable can be replaced only by one value.
Here is an example showing the use of substitution variables within PL/SQL blocks.
Suppose, the library wants to calculate its quarterly income based on its annual
income. To do this, it declares a substitution variable, which would prompt the user
to enter the figure of annual income. Based on the value entered, the quarterly
income would be calculated.
DECLARE
AnnualIncome NUMBER (7): = &annualinc;
QuarterlyInc AnnualIncome%TYPE;
-—declaring variable based on previously declared variable
using --%TYPE attribute.
BEGIN
QuarterlyInc:= AnnualIncome/4;
DBMS_OUTPUT.PUT_LINE (‘The quarterly income of the library
is: ’|| QuarterlyInc);
END;
/
In the above block, to display the quarterly income calculated, you can specify the
DBMS_OUTPUT.PUT_LINE in the PL/SQL block. DBMS_OUTPUT is an Oracle supplied
package and PUT_LINE is a procedure within it. To use this you need to specify the
information you want printed, in parentheses, following the
DBMS_OUTPUT.PUT_LINE command as shown in the above code:
iSQL*Plus host variables (also known as bind variables) are used to pass runtime
values from the PL/SQL block back to the iSQL*Plus environment. These variables
can be referenced in a PL/SQL block by placing a colon(:) before the variable.
The keyword VARIABLE is used to declare a bind variable. The syntax is:
18
© SQL Star International Ltd.
VARIABLE <variable_name> datatype
PRINT <variable_name>
Bind variables cannot be referred within the PL/SQL block of a function, procedure or
a package.
The code wherein you had calculated the quarterly income using substitution
variables can be re-written using host variables as follows:
PRINT QuarterlyInc
QUARTERLYINC
------------
20000
The above example shows the Host variable being assigned a value inside a PL/SQL
block. To assign a value to a host variable outside the Pl/SQL block following can be
done:-
SQL > VARIABLE QuarterlyInc NUMBER
SQL > Exec :QuarterlyInc := 20000
SQL> PRINT QuarterlyInc
QUARTERLYINC
------------
20000
Where,
19
© SQL Star International Ltd.
Exec stand for Execute privilege.
Nested Blocks
PL/SQL allows blocks to be nested wherever you can have an executable statement.
[This makes the nested block a statement.] Hence, the executable part of a block
can be broken down into smaller blocks. Even the exception section can contain
nested blocks.
Variable Scope
Issues that concern references to identifiers can be resolved taking into account their
scope and visibility.
By scope, we mean that region of a program unit from which an identifier can be
referenced. For instance, a variable in the declarative section can be referenced from
the exception section of that block.
The diagram shown below illustrates the concept of nested blocks and variable
scope.
20
© SQL Star International Ltd.
By visibility, we mean the regions from which an identifier can be referenced without
using a qualified name.
In the code snippet, a variable with the same name as the variable declared in the
outer block is declared in the inner block. To reference the outer block variable in the
inner block, the variable is qualified by prefixing it with the block name.
Identifiers are considered local to the PL/SQL block in which they are declared, and
are considered global to all its sub-blocks. Within the sub-block, only local identifiers
are visible because to reference the global identifiers you must use a qualified name.
If a block cannot find the identifier declared locally, it will look up to declarative
section of the enclosing block (parent block). However, the block will never look
down to the enclosed blocks (child blocks).
<<OUTER_BLK>>
DECLARE
vSal NUMBER(8,2) := 50000;
vComm NUMBER(8,2) := vSal * 0.10;
vNote VARCHAR2(200) := ‘Eligible for commission’;
BEGIN
DECLARE
vSal NUMBER(8,2) := 90000;
vComm NUMBER (4) := 0;
vAnnualComp NUMBER(8,2) := vSal + vComm;
BEGIN
vNote := ‘Manager not’||vNote;
OUTER_BLK.vComm := vSal * 0.20;
END;
vNote := ‘Salesman’||vNote;
END;
21
© SQL Star International Ltd.
/
vNote at position 1
vAnnualComp at position 2
vComm at position 1
OUTER_BLK.vComm at position 1
vComm at position 2
vNote at position 2
DECLARE
AnnualIncome NUMBER(7):= 60000;
QuarterlyInc NUMBER(8,2);
BEGIN
QuarterlyInc:= AnnualIncome/4;
DBMS_OUTPUT.PUT_LINE(‘The Quarterly income is
‘||QuarterlyInc);
END;
Here, the keywords are aligned in the same line but at different levels. This
improves readability of the code.
22
© SQL Star International Ltd.
Summary
2. Named Blocks which are compiled only once and stored in the database.
2. Executable Section where actual logic of the program lies. Keyword: BEGIN
3. Exception Section where all the errors are handled. This section is optional.
Keyword: EXCEPTION
PL/SQL variables are declared and are accessible only within that PL/SQL block.
Non- PL/SQL variables are declared outside the PL/SQL block and are available
throughout the session.
Two new datatypes FLOAT and DOUBLE introduced in this release help users in
computing complex calculations.
Nesting of blocks is allowed to have good control on the scope of the variables.
Nested Blocks can also have exception sections.
23
© SQL Star International Ltd.