You are on page 1of 29

Oracle & Distributed Databases Unit 1

Sikkim Manipal University Page No. 1


Unit 1 Oracle9i and PL/SQL
Structure:
1.1 Introduction
Objectives
1.2 Users of Oracle
1.2.1 Overview of User Management
1.2.1.1 Users and schemas
1.2.1.2 Guidelines for Creating Users
Self Assessment Questions
1.3 Overview of PL/SQL
Self Assessment Questions
1.4 Fundamentals of PL/SQL
1.4.1 Structure of PL/SQL-Blocks
1.4.2 Language Elements
Self Assessment Questions
1.5 Iterative Control in PL/SQL
1.5.1 Loop Statement
1.5.2 While Loop
1.5.3 GOTO Statement
1.5.4 FOR Loop
1.5.5 Error Handling in PL/SQL
1.5.5.1 User Defined Exceptions
1.5.5.2 Predetermined Internal PL/SQL Exceptions
Self Assessment Questions
1.6 Summary
1.7 Terminal Questions
1.8 Answers to Self Assessment Questions
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 2
1.1 Introduction
The whole point of a relational database management system (RDBMS) is
to store and supply data to clients who request it. Oracle, being one of the
more sophisticated RDBMSs out there, allows for a great deal of flexibility in
its configuration and operation. The architecture of Oracle is configured in
such a way as to ensure that client requests for data retrieval and
modification are satisfied efficiently while maintaining database integrity.
Furthermore, the architecture of Oracle needs to provide this capability to
many clients at the same time so performance is a consideration when the
architecture is configured.
The development of database applications typically requires language
constructs similar to those that can be found in programming languages
such as C, C++, or Pascal. These constructs are necessary in order to
implement complex data structures and algorithms. PL/SQL (Procedural
Language/SQL) is a procedural extension of Oracle-SQL that offers
language constructs similar to those in imperative programming languages.
Objectives
By the end of Unit 1, the learners are able to:
1. Understand creation of new users accounts in oracle database
2. Understand the expressiveness of PL/SQL,
3. Understand process query results in a tuple-oriented way,
4. Understand optimize combined SQL statements,
5. Understand the PL/SQL loops like while, for etc.
1.2 Users of Oracle
1.2.1 Overview of User Management
Any Oracle database, except those used for simple testing, also needs the
DBA to create additional users who will create schema objects or access
objects created by other users. It is the responsibility of the DBA to ensure
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 3
that user accounts are created for those individuals who need access to a
particular database, while those who should not have access are prevented
from gaining it.
1.2.1.1 Users and schemas
A schema is a collection of all objects that a user has created. Schemas
may contain objects that are segments (that is, occupy physical disk space
in a tablespace) such as a table, index, cluster, or objects that a user
creates and are stored in the data dictionary such as a sequence, stored
procedure, or function.
When you create a user account in an Oracle database, Oracle also allows
for the possibility that the user may own objects. When you grant privileges
for the user to create an object and the user exercises the privilege, the first
object created by the user also creates the users schema. Because a
schema is so closely tied to a user, the term schema is often considered
interchangeable with the user.
1.2.1.2 Guidelines for Creating Users
Although as a DBA you can create as many or as few users in your
database as you like, chances are that you will want to follow a set of rules
that would ensure that users are created for those individuals who need to
access the database, and that the initial settings of the user accounts match
the users needs.
Authentication mechanisms
One of the things that you need to consider when creating a user is what
authentication mechanism will be used to verify the users password and
whether or not the user should access the database. Oracle supports two
authentication mechanisms:
Database Authentication the DBA creates a user account in the
database for each user who needs access. When creating the user, the
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 4
DBA also specifies a password, although the user may change the
password later if needed. When the user attempts to connect to the
instance, Oracle verifies the username and password, and user is
allowed to connect to the database.
Operating Systems Authentication the management of the password
for the account can be handled outside of Oracle such as operating
system, but the DBA does not need to deal with password management.
Managing Users
Managing users is the simple process of creating, altering, or dropping
users. These tasks can be accomplished off the command line using the
CREATE USER, ALTER USER, and DROP USER command, respectively,
or by using Oracle Enterprise Manager or DBA Studio.
If a company has more than one employee who needs access to the Oracle
database, then the security of the database is a prime concern for the DBA.
The data integrity of the database and the level of security in the database
are maintained, in part, by preventing unauthorized or unintentional actions
in the database.
Database security can be divided into roughly two areas: data security and
system security. Data security includes monitoring and assigning users
permissions to the various objects in the database. System security covers
the user login process, how much disk space is assigned to each user, and
what kinds of actions each user can perform.
Creating User Accounts
To connect to the Oracle database, a user must have an Oracle database
account, also known as a username. When you create the username, you
can specify various other characteristics of the account, including a
password, a profile, default tablespaces, and disk space quotas.
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 5
Username: An Oracle database account identifier that, along with a
password, allows a user to connect to the database. The basic syntax to
create a username is as follows:
CREATE USER user <other options>;
At a minimum, you should assign a password to the account. Passwords
and the other user account options are discussed in the following sections.
Assigning Passwords
The password for the user account is typically assigned at the time the
account is created, and then changed after the user logs in for the first time.
Kiran, the DBA, creates an account for one of the new stocking managers
with an initial password of NEWSTOCK1:
create user kumar identified by newstock1;
User created.
Passwords are not case sensitive; for example, NewStok1 or newstock1
would both be stored as NEWSTOCK1 in the database. To ensure that the
password wont be easy to guess, its important to use a mixture of letters,
numbers, and punctuation characters in the password. The DBA can define
additional rules for allowable passwords by the use of a special stored
function owned by the SYS schema. For example, the DBA may require that
certain sensitive accounts such as HR have a password that is longer than
the password for any other accounts.
The DBA or user can use the ALTER USER command to change the
password:
alter user kumar identified by kum123;
User altered.
The user can change the password using the SQL*Plus PASSWORD
command.
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 6
SQL> password
Changing password for KUMAR
Old password: *********
New password: ******
Retype new password: ******
Password changed
SQL>
Creating and Assigning Profiles
Each username in the database has a profile associated with it. A profile is a
set of predefined resource parameters that can be used to monitor and
control various database resources. The following are some examples of
resources that can be controlled in a profile:
Concurrent connections to the database
Maximum failed login attempts before the account is locked
Elapsed time connected
Continuous idle time connected
CPU time used
Disk reads performed
How often a password needs to be changed
Self Assessment Questions 1.2
1. A --------- is a collection of all objects that a user has created.
a. Data
b. Attribute
c. Index
d. Schema
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 7
2. Which of the Oracle authentication mechanism is used to management
of the password for the account?
a. Database authentication
b. Network authentication
c. Operating system authentication
d. Protocol authentication
3. A -------- is a set of predefined resource parameters that can be used to
monitor andcontrol various database resources.
a. Profile
b. Username
c. Password
d. Monitor
1.3 Overview of PL/SQL
With PL/SQL, you can use SQL statements to manipulate ORACLE data
and flow-of-control statements to process the data. Moreover, you can
declare constants and variables, define subprograms (procedures and
functions), and trap runtime errors. Thus, PL/SQL combines the data
manipulating power of SQL with the data processing power of procedural
languages.
PL/SQL is a block-structured language. That is, the basic units (procedures,
functions, and anonymous blocks) that make up a PL/SQL program are
logical blocks, which can contain any number of nested sub-blocks.
Typically, each logical block corresponds to a problem or sub-problem to be
solved.
A block (or sub-block) lets you group logically related declarations and
statements. That way you can place declarations close to where they are
used. The declarations are local to the block and cease to exist when the
block completes.
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 8
[DECLARE
-- declarations]
BEGIN
-- statements
[EXCEPTION
-- handlers]
END;
The difference between SQL and PL/SQL
SQL and PL/SQL are completely different languages. SQL is a limited
language that allows you to directly interact with the database. You can
manipulate objects (DDL) and data (DML) with SQL, but SQL doesnt
include all the things that normal programming languages have such as
loops and IF...THEN statements.
That is what PL/SQL is for. PL/SQL is a normal programming language that
includes all the features of most other programming languages. But it has
one thing that other programming languages dont have, namely the easy
ability to integrate with SQL.
Whats new in Oracle SQL and PL/SQL?
Oracle SQL and PL/SQL are evolving languages that constitute the
backbone of applications written for the Oracle environment. Every version
of the Oracle database expands the features of these languages. The
production version of Oracle 10g Release 2 has recently been released. As
with previous versions, this release offers lots of new things, including the
following:
PL/SQL will probably run faster in the 9i version than it did in previous
versions.
You dont have to do anything extra to benefit from that improvement.
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 9
Oracle has made PL/SQL code run faster without requiring any
additional work on the part of the programmer.
In SQL, many new commands allow you to retrieve information more
easily than before.
Self Assessment Questions
1. PL/SQL is a ------------ structured language.
2. ------------ has made PL/SQL code run faster without requiring any
additional work on the part of the programmer.
1.4 Fundamentals of PL/SQL
Lexical Units
PL/SQL is not case-sensitive, so lower-case letters are equivalent to
corresponding upper-case letters except within string and character literals.
A line of PL/SQL text contains groups of characters known as lexical units,
which can be classified as follows:
delimiters (simple and compound symbols)
identifiers, which include reserved words
literals
comments
A delimiter is a simple or compound symbol that has a special meaning to
PL/SQL. For example, you use delimiters to represent arithmetic operations
such as addition and subtraction.
You use identifiers to name PL/SQL program objects and units, which
include constants, variables, exceptions, cursors, subprograms, and
packages. Some identifiers called RESERVED WORDS have a special
syntactic meaning to PL/SQL and so cannot be redefined. For flexibility,
PL/SQL lets you enclose identifiers within double quotes.
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 10
A literal is an explicit numeric, character, string, or Boolean value not
represented by an identifier.
Two kinds of numeric literals can be used in arithmetic expressions:
integers and reals.
String literal is a sequence of zero or more characters enclosed by
single quotes. All string literals except the null string (`') belong to type
CHAR. PL/SQL is case-sensitive within string literals.
Boolean literals are the predefined values TRUE and FALSE and the
non-value NULL (which stands for a missing, unknown, or inapplicable
value). Keep in mind that Boolean literals are not strings.
The PL/SQL compiler ignores comments but you should not. Adding
comments to your program promotes readability and aids understanding.
PL/SQL supports two comment styles: single-line and multiline.
Single-line comments begin with a double hyphen (--) anywhere on a
line and extend to the end of the line.
Multiline comments begin with a slashasterisk (/*), end with an asterisk-
slash (*/), and can span multiple lines. You cannot nest comments.
Datatypes
Every constant and variable has a data type, which specifies a storage
format, constraints, and valid range of values. PL/SQL provides a variety of
predefined scalar and composite data types. A scalar type has no internal
components. A composite type has internal components that can be
manipulated individually. PL/SQL Data types are similar to SQL's Data types
but some of the common data types are discussed again.
o (NUMBER) You can use the NUMBER data type to store fixed or
floating point numbers of virtually any size. You can specify precision,
which is the total number of digits, and scale, which determines where
rounding occurs.
Syntax: NUMBER[(precision, scale)]
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 11
o (CHAR) You can use the CHAR data type to store fixed-length character
data. The CHAR data type takes an optional parameter that lets you
specify a maximum length up to 32767 bytes.
Syntax: CHAR[(maximum_length)]
Note: You cannot use a constant or variable to specify the maximum
length; you must use an integer literal. If you do not specify the
maximum length, it defaults to 1.
o (VARCHAR2) You can use the VARCHAR2 data type to store variable-
length character data. The VARCHAR2 data type takes a required
parameter that lets you specify a maximum length up to 32767 bytes.
Syntax: VARCHAR2(maximum_length)
You cannot use a constant or variable to specify the maximum
length; you must use an integer literal.
1.4.1 Structure of PL/SQL-Blocks
PL/SQL is a block-structured language. Each block builds a (named)
program unit, and blocks can be nested. Blocks that build a procedure, a
function, or a package must be named. A PL/SQL block has an optional
declare section, a part containing PL/SQL statements, and an optional
exception-handling part. Thus the structure of a PL/SQL looks as follows
(brackets [ ] enclose optional parts):
[<Block header>]
[declare
<Constants>
<Variables>
<Cursors>
<User defined exceptions>]
begin
<PL/SQL statements>
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 12
[exception
<Exception handling>]
end;
The block header specifies whether the PL/SQL block is a procedure, a
function, or a package. If no header is specified, the block is said to be an
anonymous PL/SQL block. Each PL/SQL block again builds a PL/SQL
statement. Thus blocks can be nested like blocks in conventional
programming languages. The scope of declared variables (i.e., the part of
the program in which one can refer to the variable) is analogous to the
scope of variables in programming languages such as C or Pascal.
Declarations
Constants, variables, cursors, and exceptions used in a PL/SQL block must
be declared in the declare section of that block. Variables and constants can
be declared as follows:
<variable name> [constant] <data type> [not null] [:= <expression>];
Valid data types are SQL data types and the data type boolean. Boolean
data may only be true, false, or null. The not null clause requires that the
declared variable must always have a value different from null.
<expression> is used to initialize a variable. If no expression is specified,
the value null is assigned to the variable. The clause constant states that
once a value has been assigned to the variable, the value cannot be
changed. Example:
declare hire_date date; /* implicit initialization with null */
job_title varchar2(80) :=Salesman;
emp_found boolean; /* implicit initialization with null */
salary_incr constant number(3,2) :=1.5; /* constant */
. . .
begin . . . end;
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 13
Instead of specifying a data type, one can also refer to the data type of a
table column. For example, EMP.Empno%TYPE refers to the data type of
the column Empno in the relation EMP. Instead of a single variable, a record
can be declared that can store a complete tuple from a given table (or query
result). For example, the data type DEPT%ROWTYPE specifies a record
suitable to store all attribute values of a complete row from the table DEPT.
Such records are typically used in combination with a cursor. A field in a
record can be accessed using <record name>.<column name>, for
example, DEPT.Deptno. A cursor declaration specifies a set of tuples (as a
query result) such that the tuples can be processed in a tuple-oriented way
(i.e., one tuple at a time) using the fetch statement. A cursor declaration has
the form
cursor <cursor name> [(<list of parameters>)] is <select statement>;
The cursor name is an undeclared identifier, not the name of any PL/SQL
variable. A parameter has the form <parameter name><parameter type>.
Possible parameter types are char, varchar2, number, date and boolean as
well as corresponding subtypes such as integer. Parameters are used to
assign values to the variables that are given in the select statement.
Example:
We want to retrieve the following attribute values from the table EMP in a
tuple oriented way: the job title and name of those employees who have
been hired after a given date, and who have a manager working in a given
department. Cursor employee cur (start_date date, dno number) is
select JOB, ENAME from EMP E where HIREDATE > star_ date
and exists (select *from EMP
where E.MGR = EMPNO and DEPTNO = dno);
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 14
1.4.2 Language Elements
In addition to the declaration of variables, constants, and cursors, PL/SQL
offers various language constructs such as variable assignments, control
structures (loops, if-then-else), procedure and function calls, etc. However,
PL/SQL does not allow commands of the SQL data definition language such
as the create table statement. For this, PL/SQL provides special packages.
There are several alternatives in PL/SQL to a assign a value to a variable.
The simplest way to assign a value to a variable is
declare counter integer := 0;
. . .
begin
counter := counter + 1;
Values to assign to a variable can also be retrieved from the database using
a select statement.
select <column(s)> into <matching list of variables>
from <table(s)> where <condition>;
Instead of a list of single variables, a record can be given after the keyword
into. Also in this case, the select statement must retrieve at most one tuple.
declare employee_rec EMP%ROWTYPE;
max_sal EMP.SAL%TYPE;
begin
select EMPNO, ENAME, JOB, MGR, SAL, COMM, HIREDATE,
DEPTNO
into employee_rec
from EMP where EMPNO = 5698;
select max(SAL) into max_sal from EMP;
. . .
end;
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 15
Self Assessment Questions
1. A line of PL/SQL text contains groups of characters known as ----------
2. There are two kinds of numeric literals can be used in arithmetic
expressions of PL/SQL they are ------ and --------.
3. ------------ literals are the predefined values TRUE and FALSE and the
non-value NULL.
4. The ------------ specifies whether the PL/SQL block is a procedure, a
function, or a package.
1.5 Iterative Control in PL/SQL
PL/SQL provides iterative control and execution of PL/SQL statements in
the block. This is the ability to repeat or skip sections of a code block.
Following are the four types of iterative statements provided by the PL/SQL
The Loop statement
The WHILE Loop statement
The GOTO statement
FOR Loop
1.5.1 Loop Statement
A loop repeats a sequence of statements. The format is as follows.
LOOP
Statements
END LOOP;
The one or more PL/SQL statements can be written between the key words
LOOP and END LOOP. Once a LOOP begins to run, it will go on forever.
Hence loops are always accompanied by a conditional statement that keeps
control on the number of times it is executed. We can also build user
defined exists from a loop, where required.
Ex: LOOP
Cntr : =cntr +1;
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 16
IF cntr >100
EXIT;
END IF;
END LOOP;
EXIT statement brings the control out of loop if the condition is satisfied.
1.5.2 While Loop
The WHILE loop enables you to evaluate a condition before a sequence of
statements would be executed. If condition is TRUE then sequence of
statements are executed. This is different from the FOR loop where you
must execute the loop atleast once. The syntax for the WHILE loop is as
follows:
Syntax: WHILE <Condition is TRUE >LOOP
<Statements >
END LOOP;
Ex : DECLARE
Count NUMBER(2) : =0;
BEGIN
WHILE count <=10 LOOP
Count : =count +1;
Message('while loop executes');
END LOOP;
END;
EXIT and EXIT WHEN statement:
EXIT and EXIT WHEN statements enable you to escape out of the control of
a loop. The format of the EXIT statement is as follows:
Syntax: EXIT;
EXIT WHEN statements has following syntax
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 17
Syntax: EXIT WHEN <condition is true >;
EXIT WHEN statement enables you to specify the condition required to exit
the execution of the loop. In this case no if statement is required.
Ex-1: IF count >=10 EXIT;
Ex-2: EXIT WHEN count >=10;
1.5.3 The GOTO Statement
The GOTO statement allows you to change the flow of control within a
PL/SQL block. The syntax is as follows
Syntax: GOTO <label name>;
The label is surrounded by double brackets (<< >>) and label must not
have a semi colon after the label name. The label name does not contain a
semi colon because it is not a PL/SQL statement. But rather than identifier
of a block of PL/SQL code. You must have at least one statement after the
label otherwise an error will result. The GOTO destination must be in the
same block, at the same level as or higher than the GOTO statement itself.
Ex: IF result ='fail' THEN
GOTO failed_stud
END IF;
<<failed_stud>>
Message ('student is failed');
The entry point of the destination block is defined within << >> as shown
above, i.e. labels are written within the symbol << >>. Notice that
<<failed_stud>>is a label and it is not ended with semicolon ( ; ).
1.5.4 FOR Loop
The FOR loop will allow us to execute a block of code repeatedly until some
condition occurs. The syntax of FOR loop is as follows.
Syntax:
FOR loop_index IN [ REVERSE] low_value .. High_value LOOP
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 18
Statements to execute
END LOOP;
The loop_index is defined by oracle as a local variable of type integer.
REVERSE allows you to execute the loop in reverse order. The low_value ..
High_value is the range to execute the loop. These can be constants or
variables. The line must be terminated with loop with no semicolon at the
end of this line. You can list the statements to be executed until the loop is
executed is evaluated to false.
Ex: FOR v_count IN 1 .. 5 LOOP
Message ('for loop executes');
END LOOP;
In the above example the message 'for loop executes' is displayed five
times.
We can terminate the FOR loop permanently using EXIT statement based
on some BOOLEAN condition. Nesting of FOR loop can also be allowed in
PL/SQL. The outer loop executed once, and then the inner loop is executed
as many times as the range indicates, and then the control is returned to the
outer loop until its range expires.
Ex: FOR out_count IN 1..2 LOOP
FOR in_count IN 1..2 LOOP
Message ('nested for loop');
END LOOP;
END LOOP;
In the above example the message 'nested for loop' is displayed four times.
Let us discuss some examples from the understanding how to write a
PL/SQL block structure. Here we assume that a table called "EMP" is
created and the datas are already inserted into it.
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 19
Table name : EMP
Create table EMP
( emp_no NUMBER (3),
name VARCHAR2 (15),
salary NUMBER (6,2),
dept VARCHAR2 (15),
div VARCHAR2 (2) );
EXAMPLE-1:
DECLARE
num NUMBER (3);
sal emp.salary %TYPE;
emp_name emp.name %TYPE;
count NUMBER (2) : =1;
starting_emp CONSTANT NUMBER(3) : =134;
BEGIN
SELECT name, salary INTO emp_name, sal
FROM EMP
WHERE emp_no =starting_emp;
WHILEsal <4000.00 LOOP
Count : =count +1;
SELECT emp_no, name, salary INTO
Num, emp_name, sal FROM EMP
WHERE emp_no >2150;
END LOOP;
Commit;
END;
In the above example there are five statements in the declaration part. The
num is a integer type, sal and emp_name takes the similar data type of the
salary and name columns of EMP table respectively. Count is a variable of
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 20
type integer and takes initial value 1. Starting_emp is a constant and it is
of integer type with immediately assigned value 134.
Between BEGIN and END key words, there are some SQL executable
statements used for manipulating the table data. The SELECT statement
extracts data stored in name and salary columns of EMP table
corresponding to the employee having employee number 134. It stores
those values In the variables emp_name and sal respectively.
If sal less than 4000 then the statements within the loop will be executed.
Within the loop, there are two SQL statements, the first one increments the
count value by 1 and the second statement is a SELECT statement. The
commit statement commits the changes made to that table. The END
statement terminates the PL/SQL block.
EXAMPLE-2:
This example assumes the existence of table accounts created by using the
following SQL statements.
Create table Accounts
(accnt_id NUMBER(3),
name VARCHAR2(25),
bal NUMBER(6,2)
);
PL/SQL block
DECLARE
acct_balance NUMBER(6,2);
acct CONSTANT NUMBER(3) : =312;
debit_amt CONSTANT NUMBER(5,2) : =500.00;
BEGIN
SELECT bal INTO acct_balance
FROM Accounts
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 21
WHERE accnt_id =acct;
IF acct_balance =debit_amt THEN
UPDATE Accounts
SET bal : =bal - debit_amt
WHERE accnt_id =acct;
ELSE
Message ('insufficient amount in account');
END IF;
END;
The above example illustrates the use of IF .. THEN .. ELSE.. END IF
condition control statements.
Declaration part declares one variable and two constants. The SELECT
statement extracts the amount in the bal column of Accounts table
corresponding to account number 312, and stores that in a variable
acct_balance.
If statement checks acct_balance for sufficient amount before debiting. It
updates the table Accounts if it has sufficient amount in the balance, else it
displays a message intimating insufficient fund in the account of specified
accnt_id.
EXAMPLE-3:
This example assumes two tables, which are created by following
statements.
Create table Inventory
( prod_no NUMBER (6),
product VARCHAR2 (15),
quantity NUMBER (5) );
Create table Purchase_record
( mesg VARCHAR2 (50),
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 22
d_ate DATE );
PL/SQL block:
DECLARE
num_in_stack NUMBER(5);
BEGIN
SELECT quantity INTO num_in_stack
FROM Inventory WHERE product ='gasket';
IF num_in_stack >0 THEN
UPDATE Inventory SET quantity : =quantity - 1
WHERE product ='gasket';
INSERT INTO Purchase_record
VALUES (' One gasket purchased', sysdate);
ELSE
INSERT INTO Purchase_record
VALUES ('no gasket availabel',sysdate);
Message ( 'there are no more gasket in stack' );
END IF;
Commit;
END;
The above block of PL/SQL code does the following;
It determines how many gaskets are left in stack.
If the number left in staff is greater than zero, it updates the inventory to
reflect the sale of a gasket.
It stores the fact that a gasket was purchased on a certain date.
If the stock available is zero, it stores the fact that there are no more
gaskets for sale on the date on which such a situation occurred.
PL/SQL provides while-loops, two types of for-loops, and continuous loops.
Latter ones are used in combination with cursors. All types of loops are used
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 23
to execute a sequence of statements multiple times. The specification of
loops occurs in the same way as known from imperative programming
languages such as C or Pascal.
1.5.5 Error Handling in PL/SQL
PL/SQL has the capability of dealing with the errors that arise while
executing a PL/SQL block of code. It has a number of conditions that are
pre programmed in to it that are recognized as error conditions. These are
called internally defined exceptions. You can also program PL/SQL to
recognize user-defined exceptions.
There are two different types Error conditions ( Exceptions).
User defined error conditions / exceptions.
Predetermined internal PL/SQL exceptions.
1.5.5.1 User Defined Exceptions
User can write a set of code, which is to be executed while error occurs
when executing a PL/SQL block of code. These set of code are called user-
defined exceptions, and these are placed in the last section of PL/SQL
block called EXCEPTIONS.
The method used to recognize user-defined exceptions is as follows:
Declare a user defined exception in the declaration section of PL/SQL
block.
In the main program block for the conditions that needs special
attention, execute a RAISE statement.
Reference the declared exception with an error handling routine in
EXCEPTION section of PL/SQL block.
RAISE statement acts like CALL statement of high level languages. It has
general format
RAISE <name of exception >
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 24
When RAISE statement is executed, it stops the normal processing of
PL/SQL block of code and control passes to an error handler block of the
code at the end of PL/SQL program block ( EXCEPTION section ).
An exception declaration declares a name for user defined error conditions
that the PL/SQL code block recognizes. It can only appear in the DECLARE
section of the PL/SQL code which preceedes the key word BEGIN.
EXAMPLE :
DECLARE
---------------
zero_commission Exception;
---------------
BEGIN
-----------------
IF commission =0 THEN
RAISE zero_commission;
------------------------
EXCEPTION
WHEN zero_commission THEN
Process the error
END;
Exception handler (error handler block ) is written between the key words
EXCEPTION and END. The exception handling part of a PL/SQL code is
optional. This block of code specifies what action has to be taken when the
named exception condition occurs.
The naming convention for exception name is exactly the same as those for
variables or constants. All the rules for accessing an exception from PL/SQL
blocks are same as those for variables and constants. However, it should be
noted that exceptions cannot be passed as arguments to functions or
procedures like variables or constants.
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 25
1.5.5.2 Predetermined Internal PL/SQL Exceptions
The ORACLE server defines several errors with standard names. Although
every ORACLE error has a number, the error must be referred by name.
PL/SQL has predefined some common ORACLE errors and exceptions.
Some of them are given below:
NO_DATA_FOUND: Raised when a select statement returns zero rows.
TOO_MANY_ROWS: Raised when a select statement returns more than
one rows.
VALUE_ERROR: Raised when there is either a data type mismatch or if
the size is smaller than required size.
INVALID_NUMBER: Raised when conversion of a number to a
character string failed.
ZERO_DIVIDE: Raised when attempted to divide by zero.
PROGRAM_ERROR: Raised if PL/SQL encounters an internal problem.
STORAGE_ERROR: Raised if PL/SQL runs out of memory or if memory
is corrupted.
DUP_VAL_ON_INDEX: Raised when attempted to insert or update a
duplicate into a column that has unique index.
INVALID_CURSOR: Raised when illegal cursor operation was
attempted.
CURSOR_ALREADY_OPEN: Raised when attempted to open a cursor
that was previously opened.
NOT_LOGGED_ON: Raised when a database call was made without
being logged into ORACLE.
LOGIN_DENIED: Raised when login to ORACLE failed because of
invalid username and password.
OTHERS: This will be raised when the all other exceptions failed
to catch the errors.
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 26
It is possible to use WHEN OTHERS clause in the exception handling part
of the PL/SQL block. It will take care of all exceptions that are not taken care
of in the code.
The syntax for exception handling portion of PL/SQL block is as follows:
EXCEPTION
WHEN exception_1 THEN Statements;
WHEN exception_2 THEN Statements;
- - --- ---- -- ---
END;
In this syntax, exception_1 and exception_2 are the names of exceptions
(may be predefined or user-defined ). Statements in the PL/SQl code that
will be executed if the exception name is satisfied.
EXAMPLE-1:
This example writes PL/SQL code for validating accnt_id of Accounts table
so that it must not be left blank, if it is blank cursor should not be allowed to
move to the next field.
DECLARE
no_value exception;
BEGIN
IF : Accounts.accnt_id IS NULL THEN
RAISE no_value;
ELSE
next_field;
END IF;
EXCEPTION
WHEN no_value THEN
Message ( 'account id cannot be, blank Please enter valid data !!! ' );
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 27
go_field ( : system.cursor_field );
END;
In the above example accnt_id field of Accounts table is checked for NULL
value. If it is NULL, then RAISE statement calls exception handler
no_value. This exception name no_value is declared in DECLARE section
and defined in the EXCEPTION section of PL/SQL block by using WHEN
statement. no_value is a user-defined exception.
EXAMPLE-2:
DECLARE
balance Accounts.bal %TYPE;
acount_num Accounts.accnt_id %TYPE;
BEGIN
SELECT accnt_id bal INTO account_num, balance
FROM Accounts WHERE accnt_id >0000;
EXCEPTION
WHEN no_data_found THEN
Message ('empty table');
END;
In the above example exception is used in the PL/SQL block. This exception
is predefined internal PL/SQL exception (NO_DATA_FOUND).
Therefore, it does not require declaration in DECLARE section and RAISE
statement in BEGIN END portion of the block. Even though it is not
raised, the ORACLE server will raise this exception when there is no data in
bal and accnt_id field.
Self Assessment Questions
1. In PL/SQL iterative control statements, a --------- repeats a sequence of
statements.
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 28
2. The --------- loop enables you to evaluate a condition before a sequence
of statements would be executed.
3. The -------- loop will allow us to execute a block of code repeatedly until
some condition occurs.
4. There are -------- different types Error conditions (Exceptions) in PL/SQL.
1.6 Summary
In this unit we start the discussion on introduction of Oracle9i and PL/SQL.
Understand creation of new users accounts in oracle database. PL/SQL are
to increase the expressiveness of SQL, process query results in a tuple-
oriented way, optimize combined SQL statements, develop modular
database application programs, reuse program code, and reduce the cost
for maintaining and changing applications. Different iterative statements like
for, while, goto statement and loop statements discussed with examples.
1.7 Terminal Questions
1. Consider the Oracle DBA having ten users, How do you manage the
users?
2. Compare SQL and PL/SQL
3. Write a PL/SQL code for find Sum of N numbers using WHILE Loop
4. Mention the advantages of %TYPE declaration.
5. Illustrate with one example use of nested for loop in PL/SQL
6. How do you handle the Exception in PL/SQL? Explain
7. What are the different methods used to recognize user defined
exceptions?
1.8 Answers to Sel f Assessment Questions
Answers to Self Assessment Questions 1.2
1. block
2. Oracle
Oracle & Distributed Databases Unit 1
Sikkim Manipal University Page No. 29
Answers to Self Assessment Questions 1.3
1. lexical units
2. integers and reals
3. Boolean
4. block header
Answers to Self Assessment Questions 1.4
1. loop
2. WHILE
3. FOR
4. two
Answers to Self Assessment Questions 1.5
1. name( argument list )
2. data type

You might also like