0% found this document useful (0 votes)
17 views17 pages

Unit - 3 - ADBMS

Chapter 3 provides an overview of PL/SQL, a procedural extension of SQL that enhances its capabilities with features like control structures, exception handling, and cursors. It discusses the basic structure of PL/SQL blocks, advantages such as reduced network traffic and improved performance, and various data types used in PL/SQL. Additionally, it covers control structures including conditional, iterative, and sequential controls, as well as exception handling and cursor management.

Uploaded by

Arsh Mansuri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views17 pages

Unit - 3 - ADBMS

Chapter 3 provides an overview of PL/SQL, a procedural extension of SQL that enhances its capabilities with features like control structures, exception handling, and cursors. It discusses the basic structure of PL/SQL blocks, advantages such as reduced network traffic and improved performance, and various data types used in PL/SQL. Additionally, it covers control structures including conditional, iterative, and sequential controls, as well as exception handling and cursor management.

Uploaded by

Arsh Mansuri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CHAPTER - 3

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.

❖​ Basic Structure of PL/SQL


​ PL/SQL stands for Procedural Language/SQL. PL/SQL extends SQL by adding constructs found in
procedural languages, resulting in a structural language that is more powerful than SQL. The
basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested
within each other. Typically, each block performs a logical action in he program. A block has the
following structure:
DECLARE
/* Declarative section: variables, types, and local subprograms. */
BEGIN
/* Executable section: procedural and SQL statements go here. */
/* This is the only section of the block that is required. */
EXCEPTION
Exception handling section: error handling statements go here. */
END;

❖​ 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

❖​ 2.2 Data types

​ 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

Data Type​ Explanation​


Oracle 10g
Syntax (if applicable)
A date between Jan 1, 4712 BC
Date
and Dec 31, 9999 AD.
timestamp Includes year, month, day, hour, minute, and
Fractional second’s precision
(fractional seconds.
must be a number between 0
seconds For example:​
and 9. (default is 6)
precision) timestamp(6)

❖​ 2.3 Control structures


​ The flow of control statements can be classified into the following categories:
▪​ Conditional Control​
▪​ Iterative Control
▪​ Sequential Control

​ 2.3.1 Conditional Control


▪​ PL/SQL allows the use of an IF statement to control the execution of a block of code.
▪​ In PL/SQL, the IF -THEN - ELSIF - ELSE - END IF construct in code blocks allow specifying
certain conditions under which a specific block of code should be executed.
▪​ Syntax:
IF < Condition > THEN
< Action >
ELSIF <Condition> THEN
< Action >
ELSE
< Action >
END IF;
▪​ Example: find maximum number
DECLARE
a Number := 30;
b Number:=10
BEGIN
IF a > b THEN
DBMS_OUTPUT.PUT_LINE('Maximum=' || a);
ELSE
​ DBMS_OUTPUT.PUT_LINE('Maximum=' || b);
END IF;
END;

3
/

​ 2.3.2 Iterative Control


▪​ When user want to execute some code for specific no of times or some particular value or
condition satisfy then iterative control is used.
▪​ It contains three kinds of loop as shown below.
●​ Simple Loop
●​ While Loop
●​ For Loop

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

▪​ The FOR Loop


●​ Syntax:
FOR variable IN [REVERSE] start..end
LOOP
< Action >
END LOOP;
●​ The variable in the For Loop need not be declared. Also the increment value cannot be
specified. The For Loop variable is always incremented by 1.
●​ Example:
DECLARE
n number:=1;
BEGIN
For n in 1..5
Loop
​ Dbms_output.put_line(n);
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

CURSOR_ALREADY_OPEN Raised when we try to open an already open


cursor
DUP_VAL_ON_INDEX When you try to insert a duplicate value into
a unique column
INVALID_CURSOR It occurs when we try accessing an invalid
cursor

INVALID_NUMBER On usage of something other than number in


place of number value.

NO_DATA_FOUND Raised when select statement return zero


rows
TOO_MANY_ROWS When a select query returns more than one
row and the destination variable can take
only single value.
PROGRAM_ERROR Raised when PL/SQL has an internal problem
LOGIN_DENIED At the time when user login is denied
VALUE_ERROR When an arithmetic, value conversion,
truncation, or constraint error occurs.
ZERO_DIVIDE Raised when user try to divide by Zero

Syntax for use System defined exception:


DECLARE
BEGIN
-------
EXCEPTION
WHEN <System_Define_ExceptionName> THEN
<User Defined Action>
END

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

2. User Define Exception


This type of exception is defined by user not stored in system.
In user define exception user require to declare variable as exception data type, also need to use
raise statement to raise exception.

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.

❖​ Fetch record from Explicit cursor:


The FETCH statement place content of current row into variable.
▪​ General Syntax to fetch records from a cursor is:
Syntax:
FETCH cursor_name INTO variable_list;
❖​ Closing Explicit cursor:
▪​ After completion of fetch operation ,cursor need to close.
▪​ General Syntax for close cursor is:
Syntax:
Close <cursor_name>;
❖​ Attributes of Explicit cursor:
Cursor Attributes
Name Description
%FOUND Returns TRUE if record was fetched successfully, FALSE otherwise.
%NOTFOUND Returns TRUE if record was not fetched successfully, FALSE otherwise.
%ROWCOUNT Returns number of records fetched from cursor at that point in time.
%ISOPEN Returns TRUE if cursor is open, FALSE otherwise.

▪​ 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;

2.6 PL/SQL FUNCTIONS


▪​ A function is a named PL/SQL Block which is similar to a procedure. The major difference
between a procedure and a function is, a function must always return a value, but a
procedure may or may not return a value.
▪​ The General Syntax to create a function is:
CREATE [OR REPLACE] FUNCTION function_name (parameters {IN,OUT,INOUT} datatype]
RETURN return_datatype;
{IS, AS}
Declaration_section <variable,constant> ;
BEGIN
Execution_section
Return return_variable;
EXCEPTION
Exception handling code
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

CREATE OR REPLACE FUNCTION addition(a number,b number)


RETURN number
IS
c number;
BEGIN
c:=a+b;
RETURN c;
END;
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 function
​ ​ There are two method of executing function in pl/sql
1)calling function inside pl/sql block
For example
Declare
a number;
BEGIN
a:=addition(3,4);
dbms_output.put_line(a);
End;
Output:
7
PL/SQL procedure successfully executed

12
​ 1) like a dbms inbuilt function
For example
SELECT addition(3,4) FROM DUAL;

2.6 PL/SQL PROCEDURE


▪​ Procedure is PL/SQL block. And it is same as function but it may or may not return a value
▪​ Due to store property it is also known as Store procedure.
▪​ It means once procedure has been created it is stored in database and then after it can be
used by multiple applications.
▪​ Whenever procedure is created by user then first it compile and saved compiled format.
▪​ The General Syntax to create a function is:
CREATE [OR REPLACE] PROCEDURE proc_name (parameters {IN,OUT,INOUT} datatype]
{IS, AS}
Declaration_section <variable,constant> ;
BEGIN
Execution_section
EXCEPTION
exception section
END;
Keyword Meaning
Replace If procedure already exist then this keyword
replace it.
proc_name It is user define procedure 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

CREATE OR REPLACE Procedure print (a varchar)


IS
BEGIN
Dbms_output.put_line(a);
END;

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’);​

2.7 Procedures VS Functions


▪​ Here are a few more differences between a procedure and a function:
●​ A function MUST return a value
●​ A procedure may or may not return a value
●​ Procedures and functions can both return data in OUT and IN OUT parameters
●​ The return statement in a function returns control to the calling program and returns the
results of the function
●​ The return statement of a procedure returns control to the calling program and cannot
return a value
●​ Functions can be called from SQL, procedure cannot
●​ Functions are considered expressions, procedure are not
Packages
PL/SQL packages are schema objects that groups logically related PL/SQL types, variables and
subprograms.
Or
Package is a container of a database objects like datatypes, functions and procedures

A package will have two mandatory parts:

●​ Package specification

●​ Package body or definition

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

How to use the Package Elements/variables/procedures/functions


The package elements ( variables, procedures or functions) are accessed with the following syntax:
package_name.variable_name;

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:

Variable name table_name.column_name%type

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

You might also like