0% found this document useful (0 votes)
2 views37 pages

PL_SQL -Programming Structures

The document provides a comprehensive overview of PL/SQL, a procedural extension of SQL that combines SQL's capabilities with procedural programming features. It covers key concepts such as control structures, loops, functions, procedures, cursors, and database triggers, highlighting their syntax and usage. Additionally, it discusses the advantages of PL/SQL over SQL, including enhanced error handling and the ability to execute multiple statements in a single block.

Uploaded by

hnpatil2821969
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views37 pages

PL_SQL -Programming Structures

The document provides a comprehensive overview of PL/SQL, a procedural extension of SQL that combines SQL's capabilities with procedural programming features. It covers key concepts such as control structures, loops, functions, procedures, cursors, and database triggers, highlighting their syntax and usage. Additionally, it discusses the advantages of PL/SQL over SQL, including enhanced error handling and the ability to execute multiple statements in a single block.

Uploaded by

hnpatil2821969
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 37

PL/SQL Concepts

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).

 PL/SQL is a combination of SQL along with the procedural features of


programming languages.

 Oracle uses a PL/SQL engine to processes the PL/SQL statements.

 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.
Disadvantages of SQL
 SQL doesn’t provide the programmers with a technique of condition
checking, looping and branching.

 SQL statements are passed to Oracle engine one at a time which increases
traffic and decreases speed.

 SQL has no facility of error checking during manipulation of data.


Features of PL/SQL
 PL/SQL is basically a procedural language, which provides the functionality of
decision making, iteration and many more features of procedural
programming languages.

 PL/SQL can execute a number of queries in one block using single command.

 One can create a PL/SQL unit such as procedures, functions, packages,


triggers, and types, which are stored in the database for reuse by applications.

 PL/SQL provides a feature to handle the exception which occurs in PL/SQL


block known as exception handling block.

 PL/SQL Offers extensive error checking.


Differences between SQl & PL/SQL
SQL PL/SQL
SQL is a single query that is used to perform PL/SQL is a block of codes that used to write
DML and DDL operations. the entire program blocks/ procedure/
function, etc.
It is declarative, that defines what needs to PL/SQL is procedural that defines how the
be done, rather than how things need to be things needs to be done.
done.
Execute as a single statement. Execute as a whole block.

Mainly used to create an application.


Mainly used to manipulate data.

Cannot contain PL/SQL code in it. It is an extension of SQL, so it can contain


SQL inside it.
Structure of PL/SQL
SYNTAX:

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 ;

BEGIN -- Execution statement


c := a + b ;
dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);

END;
/
PL/SQL Control Structure
PL/SQL Control Structure

 The selection structure:


• It tests a condition, 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 or FALSE).

 The iteration structure:


• It executes a sequence of statements repeatedly as long as a condition holds true.

 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.

 Syntax for the CASE Statement:


CASE [ expression]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
PL/SQL loops
 The PL/SQL loops are used to repeat the execution of one or more statements for
specified number of times. These are also known as iterative control statements.

 There are 4 types of PL/SQL Loops.

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;

• Initial_value: Start integer value


• final _value: End integer value
Pl/sql 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.
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.

 Also, a function can be called through a procedure.


 Syntax to create a function:
CREATE [OR REPLACE] FUNCTION function_name [parameters]
[(parameter_name [IN | OUT | INOUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

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.

 In SQL, a procedure is basically a precompiled statement which is stored inside the


database. Therefore, a procedure is sometimes also called a stored procedure.

 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

The syntax for the CURSOR FOR LOOP in Oracle/PLSQL is:

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

 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 stored programs, which are automatically executed or fired when some event
occurs.
 Triggers are written to be executed in response to any of the following events.
• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
• Triggers could be defined on the table, view, schema, or database with which the event is
associated.
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.

You might also like