Unit - 3 - ADBMS
Unit - 3 - ADBMS
Pl/Sql
❖ 2.1 Introduction
Programming language/structured query language
It provide facility of procedural and function
It provides programming techniques like branching, looping, and condition check.
It is fully structured programming language.
It decreases the network traffic because entire block of code is passed to the DBA at one time
for execution.
❖ Advantages of PL/SQL
PL/SQL is development too! that not only supports SQL data manipulation but also provide
facilities of conditional checking, branching and looping.
PL/SQL sends an entire block of statements to the Oracle engine at one time. The
communication between the program block and the Oracle engine reduces considerably. This is
turn reduces network traffic. The Oracle engine gets the SQL statements as a single block, and
hence it processes this code much faster than if it got the code one sentence at a time. There, is
a definite improvement in the performance time of the Oracle engine. As an entire block of
code is passed to the DBA at one time for execution, all changes made to the data in the table
are done or undone, in one go.
PL/SQL also permits dealing with errors as required, and facilitates displaying user-friendly
messages, when errors are encountered.
PL/SQL allows declaration and use of variables in blocks of code. These variables can be used to
store intermediate results of a query for later processing, or calculate values and insert them
into an Oracle table later. PL/SQL variables can be used anywhere, either in SQL statements or in
PL/SQL blocks.
Via PL/SQL, all sorts of calculations can be done quickly and efficiently without the use of the
Oracle engine. This considerably improves transaction performance.
1
Applications written in PL/SQL are portable to any computer hardware and operating system,
where Oracle is operational. Hence, PL/SQL code blocks written for a DOS version of Oracle will
run on its UNIX version, without any modifications at all.
Support for SQL
Support for object-oriented programming
Better performance
Higher productivity
Full portability
Tight integration with Oracle
Tight security
Character Datatypes
Data Type Explanation
Oracle 10g
Syntax (if applicable)
Where size is the number of characters to store.
char(size) Maximum size of 2000 bytes.
Fixed-length strings. Space padded.
Where size is the number of characters to store.
nchar(size) Maximum size of 2000 bytes.
Fixed-length NLS string Space padded.
Where size is the number of characters to store.
nvarchar2(size) Maximum size of 4000 bytes.
Variable-length NLS string.
Where size is the number of characters to store.
Varchar2(size) Maximum size of 4000 bytes.
Variable-length string.
Long Maximum size of 2GB. Variable-length strings. (backward compatible)
Raw Maximum size of 2000 bytes. Variable-length binary strings
long raw Maximum size of 2GB. Variable-length binary strings. (backward compatible)
Numeric Datatypes
Data Type Explanation
Oracle 10g
Syntax (if applicable)
Where p is the precision and s is the scale.
Precision can range from 1 to 38. For example, number(7,2) is a number that has 5
number(p,s)
Scale can range from -84 to 127. digits before the decimal and 2 digits after the
decimal.
Where p is the precision and s is the scale.
For example, numeric(7,2) is a number that has 5
numeric(p,s) Precision can range from 1 to 38.
digits before the decimal and 2 digits after the
decimal.
Where p is the precision and s is the scale.
dec(p,s) Precision can range from 1 to 38. For example, dec(3,1) is a number that has 2 digits
before the decimal and 1 digit after the decimal.
2
Where p is the precision and s is the scale.
For example, decimal(3,1) is a number that has 2
decimal(p,s) Precision can range from 1 to 38.
digits before the decimal and 1 digit after the
decimal.
Date/Time Datatypes
3
/
▪ Simple Loop
● Syntax:
Loop
< Sequence of statements >
End loop;
● Example:
DECLARE
n number:=1;
BEGIN
Loop
Dbms_output.put_line(n);
n:=n+1;
exit when n>5;
end loop;
END;
Output:
1
2
3
4
5
PL/SQL procedure successfully completed.
▪ WHILE loop
● Syntax:
WHILE <Condition>
LOOP
< Action >
END LOOP;
4
● Example:
DECLARE
n number:=1;
BEGIN
while n<5
Loop
Dbms_output.put_line(n);
n:=n+1;
end loop;
END;
● Output:
1
2
3
4
5
PL/SQL procedure successfully completed.
5
2.3.3 Sequential Control
▪ The GOTO Statement
▪ The GOTO statement changes the flow of control within a PL/SQL block.
▪ This statement allows execution of a section of code, which is not in the normal flow of
control.
▪ The entry point into such a block of code is marked using the tags «userdefined name».
▪ The GOTO statement can then make use of this user-defined name to jump into that block
of code for execution.
Synta
Forward Jump Backward Jump
GOTO <code-block-name>; <<Code block name>>
Statement1 Statement1
<<Code block name>> GOTO <code-block-name>;
Statements2 Statements2
Example:
DECLARE
n number:=1;
BEGIN
<<s1>>
Dbms_output.put_line(n);
n:=n+1;
if n<5 then
GOTO s1;
End if;
END;
Output:
1
2
3
4
5
PL/SQL procedure successfully completed.
2.4 EXCEPTION
▪ An Exception is an error situation, which arises during program execution When an error occurs
exception is raised, normal execution is stopped and control transfers to exception-handling
part.
▪ We can also say that it is a runtime error which come during execution of a program to handle
this types of errors oracle provides Exception handling
6
▪ To handle various kinds of error PL/SQL provide exception part. it is optional part of PL/SQL
block
▪ Exception handlers are code written to handle the exception.
▪ There are two types of Exceptions:
1. System Define Exception
2. User Define Exception
1. System Define Exception
▪ Oracle has a set of pre-defined error-handler that is known as System Defined Exception
▪ This type of exception is defined by system itself we do not need to defined it
▪ Following is list of system defined exceptions
Example
DECLARE
a number(2);
b number(2);
c number(2);
7
BEGIN
a :=&a;
b:=&b;
c: =a/b;
dbms_output.put_line (‘ans is ‘||c);
EXCEPTION
WHEN ZERO_DIVIDE THEN
dbms_output.put_line (‘zero divide error’);
END;
▪ As show in above example, system defined exceptions are auto raised, user does not
required to write raise statement
▪ In above example if a is divide by zero exception will raised automatically by system
Syntax
DECLARE
<exceptionname> Exception;
BEGIN
-------
Raise <exceptionname>;
---------
EXCEPTION
WHEN <User_Define_ExceptionName> THEN
<User Defined Action>
END
Example
DECLARE
a number(5,2);
ex Exception;
BEGIN
a:=&a;
if a>0 then
dbms_output.put_line(‘a is positive’);
else
raise ex;
End if;
EXCEPTION
WHEN ex then
8
dbms_output.put_line(‘a is negetive’);
END
▪ As show in above example, ex is declared as user defined exception.it is not auto raised but
user need to write raise statement to call it
▪ In above example if value of a is less than 0 then exception will raised and it gives message
like “a is negetive”.
2.5 CURSOR
▪ Oracle Engine uses a work area for its internal processing for execute a sql statement. This
private area is called cursor.
▪ This temporary work area is used to store the data retrieved from the database, and
manipulate this data. A cursor can hold more than one row, but can process only one row at
a time. The set of rows the cursor holds is called the active set.
▪ There are two types of cursors in PL/SQL:
⧫ Explicit Cursor
⧫ Implicit Cursor
▪ Both implicit and explicit cursors have the same functionality, but they differ in the way
they are accessed.
Explicit Cursor
▪ They must be created when you are executing a SELECT statement that returns more
than one row. Even though the cursor stores multiple records, only one record can
be processed at a time, which is called as current row. When you fetch a row the
current row position moves to next row.
▪ There are four steps in using an Explicit Cursor
o DECLARE the cursor in the declaration section.
o OPEN the cursor in the Execution Section.
o FETCH the data from cursor into PL/SQL variables or records in the Execution
Section.
o CLOSE the cursor in the Execution Section before you end the PL/SQL Block.
❖ Declaration of Explicit cursor:
▪ An explicit cursor is defined in the declaration section of the PL/SQL Block
▪ Syntax:
CURSOR <cursor_name> IS <select_statement>;
o cursor _name -A suitable name for the cursor.
o Select_statement - A select query which returns multiple rows.
❖ Opening Explicit cursor:
▪ Once the cursor is created in the declaration section we can access the cursor in the
execution section of the PL/SQL program,
▪ To open cursor,use following syntax,
OPEN <cursorname>;
9
Where
Cursorname- is name of cursor which declared in declaration section.
▪ You must open cursor before fetch.
▪ These attributes can be accessed using (%) to obtain information about the state of the
cursor.
Syntax:
cursor_name%attribute
❖ Example of Explicit Cursor
Write a PL/SQL block that display all employee name and salary.
DECLARE
ename emp.empname%type;
sal emp.salary%type;
Cursor employee is select empname,salary from emp;
BEGIN
Open employee;
Loop
Fetch employee into ename,sal;
Exit when employee%notfound;
10
Dbms_output.put_line(ename||sal);
End loop;
Close employee;
END;
Implicit Cursor
▪ Implicit cursor automatically opens for each insert, update, and delete statements.
▪ There is no need to declare or open this type of cursor.
Example for implicit cursor:
DECLARE
eno emp.empno%type;
sal emp.salary%type;
BEGIN
eno:=&eno;
update emp set salary=salary+1000 where empno=eno;
if sql%found then
dbms_output.put_line(‘Salary Updated’);
else
dbms_output.put_line(‘Salary not Updated’);
end if;
END;
11
Keyword Meaning
Replace If function already exist then this keyword
replace it.
Function_name It is user define function name
Parameter It is name of argument to function
In It indicates parameter will accept from user
Out It indicates parameter will return to user
Inout It indicate that parameter will either accept
value or return value
Datatype It can be any valid datatype of argument
12
1) like a dbms inbuilt function
For example
SELECT addition(3,4) FROM DUAL;
13
❖ As ashow in above example we have created one function named Addition which take two
argument A and B.we have not specify either it is in type or out type.so by default it is in type.
❖ Execution of procedure
There are two method of executing procedure in pl/sql
1) calling procedure inside pl/sql block
For example
Declare
A number;
BEGIN
print(‘dipak’);
End;
Output:
dipak
PL/SQL procedure successfully executed
2) using Exec keyword
For example
Exec print(‘dipak’);
● Package specification
14
Package Specification
The specification is the interface to the package. It just DECLARES the types, variables, constants,
exceptions, cursors, and subprograms that can be referenced from outside the package. In other words,
it contains all information about the content of the package, but excludes the code for the
subprograms.
All objects placed in the specification are called public objects. Any subprogram not in the package
specification but coded in the package body is called a private object.
The following code snippet shows a package specification having a single procedure. You can have
many global variables defined and multiple procedures or functions inside a package.
CREATE PACKAGE p1
AS
procedure print (name varchar);
END p1;
Package Body
The package body has the codes for various methods declared in the package specification and other
private declarations, which are hidden from code outside the package.
The CREATE PACKAGE BODY Statement is used for creating the package body.
CREATE OR REPLACE PACKAGE BODY p1
AS
procedure print(name varchar);
IS
BEGIN
dbms_output.put_line(‘my name is: '|| name);
END print;
END p1;
/
Consider, we already have created above package in our database schema, the following program uses
the addition method of the p1 package:
BEGIN
P1.print(‘Rahul’);
END;
When the above code is executed at SQL prompt. It will give following output
output
Rahul
15
Advantages of PL/SQL Packages
Packages offer several advantages: modularity, easier application design, information hiding, added
functionality, and better performance.
⇒ Modularity
Packages let you encapsulate logically related types, items, and subprograms in a named PL/SQL
module. Each package is easy to understand, and the interfaces between packages are simple,
clear, and well defined. This aids application development.
⇒ Easier Application Design
When designing an application, all you need initially is the interface information in the package
specs. You can code and compile a spec without its body. Then, stored subprograms that
reference the package can be compiled as well. You need not define the package bodies fully
until you are ready to complete the application.
⇒ Information Hiding
With packages, you can specify which types, items, and subprograms are public (visible and
accessible) or private (hidden and inaccessible). For example, if a package contains four
subprograms, three might be public and one private. The package hides the implementation of
the private subprogram so that only the package (not your application) is affected if the
implementation changes. This simplifies maintenance and enhancement. Also, by hiding
implementation details from users, you protect the integrity of the package.
⇒ Added Functionality
Packaged public variables and cursors persist for the duration of a session. So, they can be
shared by all subprograms that execute in the environment. Also, they allow you to maintain
data across transactions without having to store it in the database.
⇒ Better Performance
When you call a packaged subprogram for the first time, the whole package is loaded into
memory. So, later calls to related subprograms in the package require no disk I/O. Also,
packages stop cascading dependencies and thereby avoid unnecessary recompiling. For
example, if you change the implementation of a packaged function, Oracle need not recompile
the calling subprograms because they do not depend on the package body.
Pl/Sql attributes
There are different ways you can declare the datatype of the fields.
1) You can declare the field in the same way as you declare the fieds while creating the table.
2) If a field is based on a column from database table, you can define the field_type as follows:
16
By declaring the field datatype in the above method, the datatype of the column is dynamically applied to
the field. This method is useful when you are altering the column specification of the table, because you do
not need to change the code again.
You can use also %type to declare variables and constants.
Example
17