PL_SQL -Programming Structures
PL_SQL -Programming Structures
content
PL/SQL Introduction
PL/SQL Control Structure
PL/SQL Loops
PL/SQL Function and Procedure
Exception Handling
Cursor
Database Triggers
PL/SQL Introduction
PL/SQL is a block structured language that enables developers to combine
the power of SQL with procedural statements. All the statements of a block
are passed to oracle engine all at once which increases processing speed
and decreases the traffic.
Basics of PL/SQL
PL/SQL stands for Procedural Language extensions to the Structured Query
Language (SQL).
SQL statements are passed to Oracle engine one at a time which increases
traffic and decreases speed.
PL/SQL can execute a number of queries in one block using single command.
DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;
BEGIN
null;
END;
/
Structure of PL/SQL
DECLARE
var varchar2(40) := ‘Hello PL/SQL' ;
BEGIN
dbms_output.put_line(var); --Direct PL/SQL output to a screen
END;
/
Structure of PL/SQL
DECLARE
a integer := &a ; -- Taking input from user
b integer := &b ; --Taking input from user
c integer ;
END;
/
PL/SQL Control Structure
PL/SQL Control Structure
The sequence-structure:
• It simply executes a sequence of statements in the order in which they occur.
1) IF-THEN Statement: -
Syntax:
IF condition
THEN
Statement: {It is executed when condition is true}
END IF;
Note: This syntax is used when you want to execute statements only when condition
is TRUE.
2) IF-THEN-ELSE Statement: -
Syntax:
IF condition
THEN
{...statements to execute when condition is TRUE...}
ELSE
{...statements to execute when condition is FALSE...}
END IF;
Note: This syntax is used when you want to execute one set of statements when
condition is TRUE or a different set of statements when condition is FALSE.
3) IF-THEN-ELSEIF Statement: -
Syntax:
IF condition1
THEN
{...statements to execute when condition1 is TRUE...}
ELSIF condition2
THEN
{...statements to execute when condition2 is TRUE...}
END IF;
Note: This syntax is used when you want to execute one set of statements when
condition1 is TRUE or a different set of statements when condition2 is TRUE.
Case Statement: -
• The CASE statement works like the IF statement, only using the keyword WHEN. A
CASE statement is evaluated from top to bottom. If it gets the condition TRUE, then
the corresponding THEN clause is executed and the execution goes to the END
CASE clause.
1) Basic Loop
2) Exit Loop
3) While Loop
4) For Loop
1) Basic Loop: -
Syntax:
LOOP
Sequence of statements;
END LOOP;
2) Exit Loop: -
Syntax:
LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;
3) While Loop: -
Syntax:
WHILE <condition>
LOOP statements;
END LOOP;
4) For Loop: -
Syntax:
FOR counter IN initial_value .. final_value LOOP
LOOP statements;
END LOOP;
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.
Pl/sql function
A function is a tool in SQL that is used to calculate anything to produce an output
for the provided inputs.
In SQL queries, when a function is called, it returns the resulting value. It also controls
to the calling function. However, in a function, we cannot use some DML
statements like Insert, Delete, Update, etc.
Here,
• Function_name: specifies the name of the function.
• [OR REPLACE] option allows modifying an existing function.
• The optional parameter list contains name, mode and types of the parameters.
• IN represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.
• Let's see a simple example to create a function.
CREATE or replace FUNCTION adder(n1 in number, n2 in number)
RETURN number
IS
n3 number(8);
BEGIN
n3 :=n1+n2;
RETURN n3;
END;
/
• Now, Call the function.
DECLARE
n3 number(2);
BEGIN
n3 := adder(11,22);
dbms_output.put_line('Addition is: ' || n3);
END;
/
Pl/sql Procedure
A procedure is a set of instructions which takes input and performs a certain task.
In SQL, procedures do not return a value. In Java, procedures and functions are
same and also called subroutines.
A procedure always has a name, list of parameters, and compiled SQL statements.
In SQL, a procedure does not return any value.
Pl/sqL PROCEDURE EXAMPLE
• A procedure may or may not return a value.
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
cursor
When an SQL statement is processed, Database creates a memory area known as context area.
A cursor is a pointer to this context area.
It contains all information needed for processing the statement. In PL/SQL, the context area is
controlled by Cursor.
A cursor contains information on a select statement and the rows of data accessed by it.
A cursor is used to referred to a program to fetch and process the rows returned by the SQL
statement, one at a time.
There are two types of cursors:
1) Implicit Cursors
2) Explicit Cursors
cursor
1. PL/SQL Implicit Cursors:-
The implicit cursors are automatically generated by Oracle while an SQL statement is executed, if
you don't use an explicit cursor for the statement.
These are created by default to process the statements when DML statements like INSERT,
UPDATE, DELETE etc. are executed.
Oracle provides some attributes known as Implicit cursor's attributes to check the status of DML
operations. Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.
For example: When you execute the SQL statements like INSERT, UPDATE, DELETE then the
cursor attributes tell whether any rows are affected and how many have been affected. If you run a
SELECT INTO statement in PL/SQL block, the implicit cursor attribute can be used to find out
whether any row has been returned by the SELECT statement. It will return an error if there no data
is selected.
cursor
The following table specifies the status of the cursor with each of its attribute.
Attribute Description
%FOUND Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE
affect at least one row or more rows or a SELECT INTO statement returned one or
more rows. Otherwise it returns FALSE.
%NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE
affect no row, or a SELECT INTO statement return no rows. Otherwise it returns
FALSE. It is a just opposite of %FOUND.
%ISOPEN It always returns FALSE for implicit cursors, because the SQL cursor is automatically
closed after executing its associated SQL statements.
%ROWCOUNT It returns the number of rows affected by DML statements like INSERT, DELETE, and
UPDATE or returned by a SELECT INTO statement.
cursor
2. PL/SQL Explicit Cursors:-
The Explicit cursors are defined by the programmers to gain more control over the context area.
These cursors should be defined in the declaration section of the PL/SQL block.
It is created on a SELECT statement which returns more than one row.
Following is the syntax to create an explicit cursor:
CURSOR cursor_name IS select_statement ;
Steps:
You must follow these steps while working with an explicit cursor.
• Declare the cursor to initialize in the memory.
• Open the cursor to allocate memory.
• Fetch the cursor to retrieve data.
• Close the cursor to release allocated memory.
cursor
1) Declare the cursor:
It defines the cursor with a name and the associated SELECT statement.
Syntax for explicit cursor decleration
CURSOR name IS
SELECT statement;
2) Open the cursor:
It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the SQL
statements into it.
Syntax for cursor open:
OPEN cursor_name;
cursor
3) Fetch the cursor:
It is used to access one row at a time. You can fetch rows from the above-opened cursor as follows:
Syntax for cursor fetch:
FETCH cursor_name INTO variable_list;
4) Close the cursor:
It is used to release the allocated memory. The following syntax is used to close the above-opened
cursors.
Syntax for cursor close:
Close cursor_name;
Cursor FOR loop
Description:-
“FOR LOOP” statement can be used for working with cursors. We can give the cursor name instead
of range limit in the FOR loop statement so that the loop will work from the first record of the cursor
to the last record of the cursor.
The cursor variable, opening of cursor, fetching and closing of the cursor will be done implicitly by
the FOR loop.
Syntax
DECLARE
CURSOR <cursor_name> IS <SELECT statement>;
BEGIN
FOR I IN <cursor_name>
LOOP
.
.
END LOOP;
END;
Cursor FOR loop
In the above syntax, the declaration part contains the declaration of the cursor.
The cursor is created for the ‘SELECT’ statement that is given in the cursor declaration.
In execution part, the declared cursor is setup in the FOR loop and the loop variable ‘I’ will behave
as cursor variable in this case.
Database Triggers
Advantages of Triggers
• Trigger generates some derived column values automatically
• Enforces referential integrity
• Event logging and storing information on table access
• Auditing
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions
Database Triggers
Syntax for creating 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;
Database Triggers
Here,
CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existing trigger with
the trigger_name.
{BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The
INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
[OF col_name]: This specifies the column name that would be updated.
[ON table_name]: This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various
DML statements, like INSERT, UPDATE, and DELETE.
[FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each
row being affected. Otherwise the trigger will execute just once when the SQL statement is
executed, which is called a table level trigger.
WHEN (condition): This provides a condition for rows for which the trigger would fire. This clause
is valid only for row level triggers.