0% found this document useful (0 votes)
46 views47 pages

Unit IV

PL/SQL is a programming language that is tightly integrated with Oracle Database. It allows developers to handle conditions, loops, procedures and functions. PL/SQL code is stored and executed within the database for improved performance. Key features of PL/SQL include block structure, tight integration with SQL, and support for object-oriented programming and exception handling.

Uploaded by

Soham Mahajan
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)
46 views47 pages

Unit IV

PL/SQL is a programming language that is tightly integrated with Oracle Database. It allows developers to handle conditions, loops, procedures and functions. PL/SQL code is stored and executed within the database for improved performance. Key features of PL/SQL include block structure, tight integration with SQL, and support for object-oriented programming and exception handling.

Uploaded by

Soham Mahajan
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/ 47

Chapter IV (16 M)

PL/SQL PROGRAMMING
Introduction :

 PL/SQL stands for Procedural Language/Structure Query


Language.
 PL/SQL includes procedural language elements such as
conditions and loops.
 It allows declaration of constants and variables, procedures
and functions. It can handle exceptions.
 Arrays are supported involving the use of PL/SQL
collections.
Advantages of PL/SQL
 Block structure : Block forms a unit or a logical module and
is stored in the database so that can be reusable.
 Tight Integration with SQL : PL/SQL is tightly integrated
with SQL which is popular and most widely used.
 Procedural Language Capability : PL/SQL includes
procedural language constructs such as conditional statements
and looping constructs.
 High performance : Reduce traffic between the application
and the database by sending the entire block of statements to
the database.
 High productivity : PL/SQL query can change and
automatically update the data in the database.
 Portability : PL/SQL applications can run on any operating system
and platform.
 Scalability : stored subprograms of PL/SQL increase scalability by
centralizing applications processing on the database server.
 Manageability : PL/SQL stored subprograms have only one copy
maintained on the database server which can be changed without
having to affect the applications invoking them.
 Support for Object Oriented Programming : PL/SQL supports
object oriented programming and the use of abstract data types.
 Support for Developing Web Applications : PL/SQL allows creating
applications that generate web pages.
 Support for Developing Server Pages : PL/SQL server pages allows
developing web pages with dynamic content.
 Error Handling : Handles exception effectively during the execution
of PL/SQL programs.
Block Structure of PL/SQL
Block Structure of PL/SQL
 Header :
Used only for named blocks. The header
determines the way the named block or program must be
called.
 Declaration section :
Identifies variables, cursors, and sub blocks that
are referenced in the execution and exception sections.
 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.
Execution Environment of PL/SQL
 The PL/SQL engine resides in the Oracle engine, the
Oracle engine can process not only single SQL
statements but also entire PL/SQL blocks.
 These blocks are sent to the PL/SQL engine, where
procedural statements are executed and SQL statements
are sent to the SQL executor in the Oracle engine.
 Since the PL/SQL engine resides in the Oracle engine,
this is an efficient and fast operation.
 The call to the Oracle engine needs to be made only
once to execute any number of SQL statements, if these
SQL statements are bundled inside a PL/SQL block.
Variables and Constants
 Variables :
A variable is nothing but a name given to a storage area
that our programs can manipulate.
Each variable in PL/SQL has a specific data type, which
determines the size and the layout of the variable's memory.
PL/SQL variables must be declared in the declaration
section.
PL/SQL allocates memory for the variable's value and the
storage location is identified by the variable name.
The syntax for declaring a variable is −
variable_name [CONSTANT] datatype [NOT NULL] [:= |
DEFAULT initial_value]
Variables and Constants
Scope of Variables :
There are two types of variable scope −
Local variables − Variables declared in an inner block and not
accessible to outer blocks.
Global variables − Variables declared in the outermost block or
a package.
Constants
A constant holds a value that once declared, does not change in
the program.
A constant declaration specifies its name, data type, and value,
and allocates storage for it.
A constant is declared using the CONSTANT keyword. It requires
an initial value and does not allow that value to be changed.
Variables and Constants
DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;
PL/SQL Output
We can declare a host variable and reference it in a PL/SQL block and then displayit
contents using the PRINT command.
There is other simple option for displaying information from a PL/SQL block is
DBMS_OUTPUT.PUT_LINE.

Printing Text String :


To print text string we use single quotation.
BEGIN
DBMS_OUTPU.PUT_LINE(‘Output Tested’);
END;
Printing PL/SQL Variables :
To print variable no need to write single quotation.
DECLARE
var_number number := 1
BEGIN
DBMS_OUTPUT.PUT_LINE(var_number);
END;
PL/SQL Input
We use substitution variable for accepting input using PL/SQL substitution variable is
prefixed with ‘&’ Operator
Accept Text String :
To accept text string we use single quotation.
DECLARE
V_Name varchar(50):=‘&Name’
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Accepted rName=‘||_Name);
END;
Accept Number:
To accept number variable no need to write single quotation.
DECLARE
var_number number := &umber
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Accepted
Number=‘||var_number);
END;
PL/SQL Expressions and comparisons
1. Comparison Expressions :
Operators:
Operators Description
< Less Than
<= Less than equals to
> Greater Than
>= Greater than equals to
<> Not equals to

Logical Expressions :
Operators:
Operators Descriptions
AND AND operations
OR Or Operation
NOT NOT Operation
PL/SQL Expressions and comparisons
1. Range Comparison Expressions :
Operators:
Operators Description
IN Use to check variable is equivalent with multiple
available values given in IN expression
BETWEEN Used to check variable is equivalent with given
range of values.

Nullness Comparison Operators :


Operators:
Operators Descriptions
IS NULL Returns true if value of variable is null
IS NOT NULL Returns true if value of variable is contains some
not null value.
PL/SQL Expressions and comparisons
1. EXIST Expressions :
these operators can check whether query
result is available or not.
Operators:
Operators Description

EXIST Returns true if query returns more then one tuple

NOT EXIST Returns true if query returns no row.


PL/SQL Data Types
PL/SQL Scalar Data Types and Subtypes
Built –In data types :
PL/SQL Scalar Data Types and Subtypes come under the
following categories −
 Numeric :
Numeric values on which arithmetic operations are performed.
 Character :
Alphanumeric values that represent single characters or strings
of characters.
 Boolean :
Logical values on which logical operations are performed.
 Date time :
Dates and times.
PL/SQL Scalar Data Types and Subtypes
Built –In data types :
PL/SQL Scalar Data Types and Subtypes come under the
following categories −
 Numeric :
A. Integer number of various sizes:
This type of system is used to store natural number
which is not having any decimal values.

Data Abbreviation Description Range


Type
INTEGER INT Integer numerical with -2,147,483,648 to
precision 10 2,147,483,647
PL/SQL Scalar Data Types and Subtypes
 Numeric :
B. Formatted Numbers:
This system used for storing some special numbers which
may be of greater size than integer and floating numbers.
e.g. number(i,j) where i is precision and j is scale.

Data Type Abbreviati Description Range


on
NUMBER(P,S) NUM(P,S) Exact numerical with precision P and scale -
S
NUMERIC NUM NUM is equivalent to NUM (15,0) -

NUMERIC(P) NUM(P) NUM is equivalent to NUM(p,0) -


Control Structure
 The control structures decides the execution flow of
the program depending on the condition defined by
the programmer.

 Following control structures are used in PL/SQL :


 Selection control structure
 Iteration control structure
 Sequence control structure
Conditional Control Structure
 IF Statement :
an IF statement executes a sequence of statements depending on the
values of a condition.
Syntax : IF condition
statement;
END IF
 IF –THEN Statement :
IF – THEN executes the statement or a block of statements if the
condition is true.
Syntax : IF condition THEN
statement;
statement;
.
.
END IF;
Example :
 SQL>
DECLEAR
num1 Number(6);
num2 Number(6);
BEGIN
num1:= 16;
num2:= 20;
IF num1<num2 THEN
DBMS_OUTPUT.PUT_LINE(’num1 is less than’);
END IF;
END;
IF – THEN – ELSE Statement
Syntax :
IF condition THEN
true statements;
ELSE
false statements;
END IF
Example :
DECLARE
percent Number(6);
BEGIN
percent:=60;
IF percent >40 THEN
DBMS_OUTPUT.PUT_LINE(‘PASS’);
ELSE
DBMS_OUTPUT.PUT_LINE(‘FAIL’);
END IF;
END;
Nested IF-THEN-ELSE Statement.
 IF statement can also be nested inside other IF statements. This
allows us to check more than one condition in a series and execute
the appropriate block of statements depending on the condition.
 Syntax :
IF(Condition ) THEN
…..
ELSE IF(Condition) THEN
……
ELSE IF(Condition) THEN
…...
END IF;
CASE Statement
 The CASE statement can be used when a single condition may
evaluate.
 CASE statement in PL/SQL has following forms:
1. Simple CASE
2. Searched CASE
 Simple CASE : It executes the block of statements where the
match for the selector is found. Default block is executed if no
match is found for the selector.
 Simple CASE Syntax :
CASE SELECTROR
WHEN expr1 THEN statement 1;
WHEN expr2 THEN statement 2;
.
.
ELSE statement n;
END CASE;
 Search CASE Syntax :
CASE
WHEN search condition THEN
statement 1;
WHEN search condition THEN
statement 1;
.
.
WHEN search condition THEN
statement n;
END CASE
Iterative Control Loop
 A. Simple Loop :
Loop
Statements;
End Loop
 Example :
Declare
C number(10);
Begin
C:=11;
Loop
C:=c+11;
DBMS_OUTPUT.PUT_LINE(C);
If c>110 then
Exit;
End if;
End loop;
End;
While loop
 Syntax :
WHILE condition LOOP
statements;
END LOOP;
Example : Declare
C number(10);
Begin
C:=11;
while C<110
loop
C:=c+11;
DBMS_OUTPUT.PUT_LINE(C);
End loop;
End;
For Loop
 Syntax :
For counter IN lower_bound .. Upper_bound LOOP
Statements;
END LOOP;
 Example :
DECLARE
qans number(10);
BEGIN
ans :=5;
FOR num IN 1 .. 10 LOOP
ans := ans +5;
DBMS_OUTPUT.PUT_LINE(ans);
END LOOP;
END
Cursor
 Introduction :
The cursor is a pointer to the private area in SQL that
stores information about processing a specific DML statement.
The drawback with select statement is that it returns only
one row at a time in a PL/SQL block.
Cursors are capable of holding more than one row.
Set of rows retrieved in such an area in called the active set
and its size depends on the number of rows retrieved by the
search condition of the query.
Cursors can be classified as :
1. Implicit Cursor
2. Explicit Cursor
Implicit Cursor
 Implicit cursor is a session cursor which is opened every time you
run a select of DML statement in the PL/SQL block.
 An implicit cursor closes after its associated statements run but its
attributes values remain available until another select or DML
statement is executed.
 Implicit cursor attributes :
1. SQL%ISOPEN 2. SQL%FOUND 3. SQL%NOTFOUND
4. ROWCOUNT
Syntax :
SQLattribute
Example:
SQL%ISOPEN
 Example :

Begin
update emp set salary= salary+1000 where
dept_no = 101;
if SQL%FOUND then
DBMS_output.put_line(‘Salary Updated’);
else
DBMS_output.put_line(‘Salary Not Updated’);
end if
END
Explicit Cursor
 The cursors which declared by users is called as Explicit
Cursor.
 Steps to Declare Cursor:
 Step 1: Declare the cursor in declaration cursor.
Example : CURSOR c_emp IS select empno, ename, salary
from emp;
 Step 2 : Open the cursor in execution section.
Example : OPEN cursor_name;
 Step 3: FETCH the data from cursor into PL/SQL variable or
records in the execution section.
Example : FETCH cursor_name into record name;
 Step 4: CLOSE the cursor in the execution section before we
end the PL /sql BLOCK.
Cursor for loop
 When ‘for’ loop is used in cursor we do not have to declare a
record of variables to store the cursor values.
Syntax :
FOR record IN cursor_name
LOOP
action 1
action 2

END LOOP
Parameterized Cursor
 Parameterized cursors are static cursors that can accept passed in
parameter values when they are opened.
 Example :
DECLARE
cursor c(no number) is select * from emp_information where
emp_no = no;
tmp emp_information%rowtype;
BEGIN
OPEN c(4);
FOR tmp IN c(4) LOOP
dbms_output.put_line('EMP_No: '||tmp.emp_no);
dbms_output.put_line('EMP_Name: '||tmp.emp_name);
dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
END Loop;
CLOSE c;
END;
Procedures
 Stored procedure is a group of SQL statement which can be
executed repeatedly.
 The parameters makes the stored procedure more flexible and
useful. Stored procedures can increase productivity by writing once
and using it many times.
Syntax :
Create procedure procedure_name
[(param1, param 2])
IS
declaration section;
BEGIN
execution section;
EXCEPTION
exception section;
Advantages
 Stored procedure can share logic with different
applications.
 Stored procedure can isolate users from data table.
 Stored procedure can provide security that means users
can input data and can also they can change it but they
could not write procedure.
 Stored procedure can be used to improve performance.
 Stored procedure is fast because it is precompiled.
 It improves reliability and reduce development time.
 Reduce network usage among servers and clients.
Executing Stored Procedure
 Using EXECUTE ;
EXECUTE proc1;

 Using CALL :
CALL proc1;

 Using PL/SQL Block :


begin
proce1();
end;
Function
 Stored function or user defined function are very similar to
procedures, except that a functions returns a value to the environment
from where it is called.
 Function parameters :
 IN : The parameter can be referenced by the procedure or function.
 OUT : The parameter can not be referenced by the procedure or
function, but the value of the parameter can be overwritten by the
procedure or function.
 IN OUT : The parameter can be referenced by the procedure or function
and the value of the parameter can be overwritten by the procedure or
function.
Creating Function
 Syntax :
create function function_name( param1, param2) return
return_type IS / AS
declaration section;
Begin
execution section;
Exception
exception seciton;
End;
 Example :
create function sum(a number, b number) return number
IS
begin
return(a+b);
end;
 Executing Function :
begin
DBMS_output.put_line(‘Result is’||sum(23,45));
end;
 Deleting a function :
Drop function function_name;
Drop function sum;
Difference between Function &
Procedure
Sr. Function Procedure
No.
1 A Function must always return A Procedure can not return a
a value value
2 The return statement in a The return statement of a
function control to the calling procedure returns control to the
program and returns the calling program but no value
results of the function
3 Functions can be called from Procedure cannot be called from
SQL SQL
4 Functions are considered Procedure can not be considered
expressions as expressions.
Database Trigger
 A trigger is a stored procedure in database which automatically
invokes whenever a special event in the database occurs.
 Syntax:
 create trigger [trigger_name]
 [before | after]
 {insert | update | delete} on
 [table_name] [
 for each row]
 [trigger_body]
 Explanation of syntax:
 create trigger [trigger_name]: Creates or replaces an existing
trigger with the trigger_name.
 [before | after]: This specifies when the trigger will be executed.
 {insert | update | delete}: This specifies the DML operation.
 on [table_name]: This specifies the name of the table associated
with the trigger.
 [for each row]: This specifies a row-level trigger, i.e., the trigger
will be executed for each row being affected.
 [trigger_body]: This provides the operation to be performed as
trigger is fired
Achievement of unit
 Write simple PL/SQL code using control
structure and handle various exceptions.

 Create cursor for retrieving multiple records.

 Create and execute stored procedures and


functions.

 Create and apply database trigger using PL/SQL.

You might also like