0% found this document useful (0 votes)
62 views

Unit 4

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)
62 views

Unit 4

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

Advanced Database Management System Notes

Unit-4
PL/SQL Concept
❖ PL/SQL Introduction
PL/SQL is a block structured language. The programs of PL/SQL are logical blocks that can
contain any number of nested sub-blocks. Pl/SQL stands for "Procedural Language extension
of SQL" that is used in Oracle.

PL/SQL includes procedural language elements like conditions and loops. It allows
declaration of constants and variables, procedures and functions, types and variable of those
types and triggers. It can support Array and handle exceptions (runtime errors). After the
implementation of version 8 of Oracle database have included features associated with object
orientation.

You can create PL/SQL units like procedures, functions, packages, types and triggers, etc.
which are stored in the database for reuse by applications.

❖ PL/SQL Datatypes
The PL/SQL variables, constants and parameters must have a valid data type, which specifies
a storage format, constraints, and a valid range of values.

PL/SQL Scalar Data Types are listed as following:


Sr.
Datatype & Description
No.
Numeric
1.
Numeric values on which arithmetic operations are performed.
Character
2.
Alphanumeric values that represent single characters or strings of characters.
Boolean
3.
Logical values on which logical operations are performed.
Datetime
4.
Dates and times.

• PL/SQL Variables
A variable is a meaningful name which facilitates a programmer to store data temporarily during
the execution of code. It helps you to manipulate data in PL/SQL programs. It is nothing except
a name given to a storage area. Each variable in the PL/SQL has a specific data type which
defines the size and layout of the variable's memory.

A variable should not exceed 30 characters. Its letter optionally followed by more letters, dollar
signs, numerals, underscore etc.

1. It needs to declare the variable first in the declaration section of a PL/SQL block before
using it.
2. By default, variable names are not case sensitive. A reserved PL/SQL keyword cannot be
used as a variable name.
Declare a Variable
You must declare the PL/SQL variable in the declaration section or in a package as a global
variable. After the declaration, PL/SQL allocates memory for the variable's value and the
storage location is identified by the variable name.
Page 1 of 14
Advanced Database Management System Notes

Syntax:
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value];

Example:
Radius Number:= 5;
Date_of_birth date;

• PL/SQL Constants
A constant is a value used in a PL/SQL block that remains unchanged throughout the program.
It is a user-defined literal value. It can be declared and used instead of actual values.

Syntax:
constant_name CONSTANT datatype := VALUE;

Constant_name: it is the name of constant just like variable name. The constant word is a
reserved word and its value does not change.
VALUE: it is a value which is assigned to a constant when it is declared. It can not be assigned
later.

Example:
pi constant number:= 3.141592654;

• PL/SQL Block
In PL/SQL, the code is not executed in single line format, but it is always executed by grouping
the code into a single element called Blocks. In this tutorial, you are going to learn about these
blocks.

Blocks contain both PL/SQL as well as SQL instruction. All these instructions will be
executed as a whole rather than executing a single instruction at a time.

PL/SQL blocks have a pre-defined structure in which the code is to be grouped.

A PL/SQL block has up to three different sections, only one of which is mandatory:
Declaration section
Identifies variables, cursors, and subblocks that are referenced in the execution and exception
sections. Optional.
Execution section
Statements the PL/SQL runtime engine will execute at runtime. Mandatory.
Exception section
Handles exceptions to normal processing (warnings and error conditions). Optional.

Page 2 of 14
Advanced Database Management System Notes

DECLARE -- Optional

<Declaration Section>

BEGIN -- Mandatory

<Executable Commands>

EXCEPTION -- Optional

<Exception Handling>

END; -- Mandatory

Example:

Input:
DECLARE
-- variable declaration
message varchar2(20):= 'Welcome to L.J.University';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
Output:
Welcome to L.J.University
PL/SQL procedure successfully completed.

• Advantages of PL/SQL
Block Structures: PL SQL consists of blocks of code, which can be nested within each other.
Each block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the
database and reused.
Procedural Language Capability: PL SQL consists of procedural language constructs such as
conditional statements (if else statements) and loops like (FOR loops).

Better Performance: PL SQL engine processes multiple SQL statements simultaneously as a


single block, thereby reducing network traffic.

Page 3 of 14
Advanced Database Management System Notes

Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a
PL/SQL program. Once an exception is caught, specific actions can be taken depending upon
the type of the exception or it can be displayed to the user with a message.

❖ PL/SQL Control Structures


According to the structure theorem, any computer program can be written using the basic control
structures, which can be combined in any way necessary to deal with a given problem.

The Conditional Structure tests a condition, and then executes one sequence of statements
instead of another, depending on whether the condition is true or false. A condition is any
variable or expression that returns a Boolean value (TRUE, FALSE, or NULL).

The Iteration Structure executes a sequence of statements repeatedly as long as a condition


holds true.

The Sequence Structure simply executes a sequence of statements in the order in which they
occur.

Control
Structures

Conditional Iterative Sequential


Control Control Control

• Conditional Control
Conditional control allows you to control the flow of the execution of the program based on a
condition. In programming terms, it means that the statements in the program are not executed
sequentially. Rather, one group of statements, or another will be executed, depending on how
the condition is evaluated.
There are three forms of IF statements - IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF.

IF-THEN
This construct tests a simple condition. If the condition evaluates to TRUE, one or more lines of
code are executed. If the condition evaluates to FALSE, program control is passed to the next
statement after the test. The following code illustrates implementing this logic in PL/SQL.

Input:
YouIfmay
var1>1
codethen
nested IF-THEN statements as shown in the following.
var2:=var1+2;
END IF;
Page 4 of 14
Advanced Database Management System Notes

IF-THEN-ELSE
This construct is similar to IF, except that when the condition evaluates to FALSE, one or more
statements following the ELSE are executed. The following code illustrates implementing this
logic in PL/SQL.

DECLARE
a number:=1;
b number:=2;
BEGIN
If a>b then
dbms_output.put_line(“a is maximum.”);
ELSE
dbms_output.put_line(“b is maximum.”);
END IF;
END;

IF-THEN-ELSIF
This format is an alternative to using the nested IF-THEN-ELSE construct. The code in the
previous listing could be reworded to read:

DECLARE
a number:=1;
b number:=2;
c number:=3;
BEGIN
If a>b AND a>c then
dbms_output.put_line(“a is maximum.”);
ELSEIF b>c then
dbms_output.put_line(“b is maximum.”);
ELSE
dbms_output.put_line(“c is maximum.”);
END IF;
END;

• Iterative Control
LOOP statements let you execute a sequence of statements multiple times. There are three forms
of LOOP statements: LOOP, WHILE-LOOP, and FOR-LOOP.

Page 5 of 14
Advanced Database Management System Notes

LOOP
The simplest form of LOOP statement is the basic (or infinite) loop, which encloses a sequence
of statements between the keywords LOOP and END LOOP, as follows:

LOOP
statement1;
statement2;
statement3;
...
END LOOP;

WHILE-LOOP
A WHILE loop has the following structure:

WHILE <condition>LOOP
statement 1;
statement 2;
statement 3;
...
statement N;
END LOOP;

Example:

DECLARE
v_counter NUMBER := 1;
BEGIN
WHILE v_counter < 5 LOOP
dbms_output.put_line('v_counter = ' || v_counter);
-- increment the value of v_counter by one
v_counter := v_counter + 1;
END LOOP;
END;

Page 6 of 14
Advanced Database Management System Notes

FOR-LOOP
Whereas the number of iteration through a WHILE loop is unknown until the loop completes,
the number of iterations through a FOR loop is known before the loop is entered. FOR loops
iterate over a specified range of integers. The range is part of an iteration scheme, which is
enclosed by the keywords FOR and LOOP.

FOR counter IN [REVERSE] lower_bound..upper_bound LOOP


statement 1;
statement 2;
statement 3;
...
statement N;
END LOOP;
/

Example:

SET SERVEROUTPUT ON
DECLARE
cnt_employee NUMBER;
BEGIN
SELECT COUNT(*) INTO cnt_employee FROM employee;
FOR v_counter IN 1..cnt_employee LOOP
DBMS_OUTPUT.PUT_LINE('v_counter = ' || v_counter);
END LOOP;
END;
/

• Sequential Control
Normally, execution proceeds sequentially within the block of the code. But, this sequence can
be changed conditionally as well as unconditionally. To alter the sequence unconditionally, the
GOTO statement can be used.

GOTO
PL/SQL also includes a GOTO statement to branch from one point to another.
Syntax:
GOTO <label>;
Where “<label>” is a label defined in the PL/SQL block.

Page 7 of 14
Advanced Database Management System Notes

Example:

SET SERVEROUTPUT ON
DECLARE
v_counter NUMBER(2) := 1;
BEGIN
LOOP
v_counter := v_counter+1;
IF v_counter > 5 THEN
GOTO PRINT1; -- print v_counter 5 times
END IF;
dbms_output.put_line('v_counter = ' || v_counter);
END LOOP;
<< PRINT1>>
END;

❖ PL/SQL Exceptions

Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is
violated by a program. For example, the predefined exception NO_DATA_FOUND is raised
when a SELECT INTO statement returns no rows.

User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using either a RAISE
statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is:
DECLARE
my-exception EXCEPTION;

❖ Cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.

In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
has the attributes like %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL
cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS,
designed for use with the FORALL statement. The following table provides the description of
the most used attributes:

Page 8 of 14
Advanced Database Management System Notes

Attribute Description

%FOUND Returns TRUE if an INSERT, UPDATE, or DELETE statement affected


one or more rows or a SELECT INTO statement returned one or more
rows. Otherwise, it returns FALSE.

%NOTFOUND The logical opposite of %FOUND. It returns TRUE if an INSERT,


UPDATE, or DELETE statement affected no rows, or a SELECT INTO
statement returned no rows. Otherwise, it returns FALSE.

%ISOPEN Always returns FALSE for implicit cursors, because Oracle closes the
SQL cursor automatically after executing its associated SQL statement.

%ROWCOUNT Returns the number of rows affected by an INSERT, UPDATE, or


DELETE statement, or returned by a SELECT INTO statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the
example.

Example:
Select * from customers;
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
The following program would update the table and increase salary of each customer by 500 and
use the SQL%ROWCOUNT attribute to determine the number of rows affected:

DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/

Page 9 of 14
Advanced Database Management System Notes

When the above code is executed at SQL prompt, it produces the following result:
6 customers selected
PL/SQL procedure successfully completed.

If you check the records in customers table, you will find that the rows have been updated:
Select * from customers;

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmedabad 2500.00
2 Khilan 25 Delhi 2000.00
3 Kaushik 23 Kota 2500.00
4 Chaitali 25 Mumbai 7000.00
5 Hardik 27 Bhopal 9000.00
6 Komal 22 MP 5000.00
Explicit Cursors
Explicit cursors are programmer defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the PL/SQL Block.

The syntax for creating an explicit cursor is:


CURSOR cursor_name IS select_statement;

Working with an explicit cursor involves four steps:


• Declaring the cursor for initializing in the memory
• Opening the cursor for allocating memory
• Fetching the cursor for retrieving data
• Closing the cursor to release allocated memory
Declaring the Cursor
CURSOR c_customers
IS
SELECT id, name, address FROM customers;
Opening the Cursor
OPEN c_customers;
Fetching the Cursor
FETCH c_customers INTO c_id, c_name, c_addr;
Closing the Cursor
CLOSE c_customers;

❖ Trigger
Trigger is invoked by Oracle engine automatically whenever a specified event occurs. Trigger is
stored into database and invoked repeatedly, when specific condition match. Triggers are written
to be executed in response to any of the following events.

Page 10 of 14
Advanced Database Management System Notes

Syntax to Create a Trigger:

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Example:

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
Output: Trigger created.

❖ Package
Packages are schema objects that groups logically related PL/SQL types, variables, and
subprograms.
A package will have two mandatory parts −
• Package Specification

Page 11 of 14
Advanced Database Management System Notes

• Package Body or Definition

Package Specification

CREATE PACKAGE cust_sal AS


PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/
Output:
Package created.

Package Body

CREATE OR REPLACE PACKAGE BODY cust_sal AS

PROCEDURE find_sal(c_id customers.id%TYPE) IS


c_sal customers.salary%TYPE;
BEGIN
SELECT salary INTO c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line('Salary: '|| c_sal);
END find_sal;
END cust_sal;
/
Output:
Package body created.
PL/SQL procedure successfully completed.

❖ Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks. It is just like procedures in other programming languages.
Syntax for creating procedure:

CREATE [OR REPLACE] PROCEDURE procedure_name


[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Page 12 of 14
Advanced Database Management System Notes

Example:

CREATE OR REPLACE PROCEDURE "INSERTUSER"


(id IN NUMBER,
name IN VARCHAR2)
IS
BEGIN
insert into user values(id,name);
END;
/
Output:
Procedure created.

Let's see the code to call above created procedure.

BEGIN
insertuser(101,'Disha');
dbms_output.put_line('record inserted successfully');
END;
/

Now, see the "USER" table, you will see one record is inserted.
ID Name
101 Rahul

Destroy PL/SQL Procedure


Syntax:
DROP PROCEDURE procedure_name;

Example:
DROP PROCEDURE pro1;
❖ Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between
procedure and a function is, a function must always return a value, and on the other hand a
procedure may or may not return a value. Except this, all the other things of PL/SQL procedure
are true for PL/SQL function too.
Syntax:

CREATE [OR REPLACE] FUNCTION function_name [parameters]


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name]; Page 13 of 14
Advanced Database Management System Notes

Example:

CREATE OR REPLACE FUNCTION add(n1 in number, n2 in number)


RETURN number
IS
n3 number(8);
BEGIN
n3 :=n1+n2;
RETURN n3;

Now write another program to call the function.

DECLARE
n3 number(2);
BEGIN
n3 := add(11,22);
dbms_output.put_line('Addition is: ' || n3);
END;
/
Output:
Addition is: 33
Statement processed.
0.05 seconds

Destroy PL/SQL Function


Syntax:
DROP FUNCTION function_name;

Example:
DROP FUNCTION add;

Page 14 of 14

You might also like