Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
177 views

Oracle SQL plsql-264-349

PL/SQL is a procedural extension of SQL that allows developers to write blocks of code that perform operations on data in an Oracle database. It combines the SQL data manipulation power with procedural language elements like conditions and loops. A PL/SQL block contains a declarative part, an executable part, and an optional exception-handling part. It allows developers to define variables, cursors, and subprograms to manipulate data in the database. PL/SQL supports both procedural and non-procedural elements and can be used for both server-side and client-side development.

Uploaded by

Pravin Saini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
177 views

Oracle SQL plsql-264-349

PL/SQL is a procedural extension of SQL that allows developers to write blocks of code that perform operations on data in an Oracle database. It combines the SQL data manipulation power with procedural language elements like conditions and loops. A PL/SQL block contains a declarative part, an executable part, and an optional exception-handling part. It allows developers to define variables, cursors, and subprograms to manipulate data in the database. PL/SQL supports both procedural and non-procedural elements and can be used for both server-side and client-side development.

Uploaded by

Pravin Saini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

By:Mr.

Krishna Reddy DURGASOFT

PL/SQL
• PL/SQL is a procedural extension to a non-procedural language SQL.
• PL/SQL is one of the utility of Oracle dbserver and it is not a tool like
SQL*plus.
• It is a block-structured language.
• PL/SQL block is a logical collection of procedural as well as non-
procedural statements. It is a data processing language, but SQL is a
powerful Data Manipulation Language.
• PL/SQL is having all the features of procedural language as well as all
non-procedural features(because of SQL support).
• PL/SQL can used for both Server-Side and Client-Side Development.
• PL/SQL block is a logical collection of procedural as well as non-
procedural statements.

Types of valid statements of PL/SQL block


• SQL statements(non procedural statements)
• Non-SQL statements(procedural statements)

Block structure approach


• The basic units that make up a PL/SQL program are logical blocks.
• The block in PL/SQL can be nested with one another.
• A block groups related declarations and statements into one single
unit.
• The basic parts of a PL/SQL block are
o Declarative part(optional)
o Executable part(Mandatory)
o Exception Handling(optional)

Declarative part
• It is used to define user defined types, variables which can be used, in
the executable part for further manipulations.
Executable Part
• All procedural statements are included between the BEGIN and END
statement.
• It must have one executable statement.
Exception Handling Part
• Error that occur during execution are dealt in the exception handling
part.

264 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Notes:
• A PL/SQL program is a logical block, which contain any number of
nested sub blocks.
• Block can be nested in the executable and exception handling parts of
a PL/SQL block, or a sub program.
• A PL/SQL is marked with either a “DECLARE” or “BEGIN” keyword and
ends with the keyword “END”
• Only BEGIN and END keywords are mandatory.
• A semicolon(;) has to be placed after the “END” keyword.
Block syntax
SQL>DECLARE
[Variable declarations;
Cursor declaration;
User_defined exception;]
BEGIN
<SQL statements;>
PL/SQL statement
EXCEPTION
Action to perform when errors occurs.
END;
• Only executable section is required.
• The declarative and exception handling section are optional.
• We can define local sub programs in the declarative part of any block.
• However , we can call local subprograms only from the block in which
they are define.

A simple PL/SQL Block


SQL> BEGIN
NULL;
END;

NULL block.

SQL> BEGIN
RETURN;
END;
→BLOCK with RETURN clause.

SQL>DECLARE
BEGIN
NULL;
END;

SQL>DECLARE

265 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

BEGIN
NULL;
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
Executing statements and PL/SQL blocks from SQL*Plus
• Place a semicolon(;) at the end of the SQL statement or PL/SQL
control statement.
• Use a Forward slash(/) to run the Anonymous PL/SQL block in
SQL*plus buffer.
• Place a period(.) to close a SQL*Plus Buffer with out running the
PL/SQL program.
• A PL/SQL block is treated as one continuous statement in the SQL*plus
buffer.
• Semicolon within the PL/SQL block does not closes or Runs the SQL
Buffer.
• In PL/SQL an Error is called as an Exception.
• Sections keywords “DECLARE”,”BEGIN”, and “EXCEPTION” should not
contain A semicolon.
• “END” and all other PL/SQL statements should be applied with a
semicolon at the End.
Note:
• Declaration part of PL/SQL block is optional ,but the body of the
PL/SQL is must.(The area between begin and end is called as body of
the Pl/SQL block.
• Every PL/SQL block is terminated by END statement followed by a
semicolon.
• PL/SQL is not a data formatting language.
Types of blocks in PL/SQL
• A PL/SQL program can be written in various types of blocks, they are
Anonymous block
• The block having no name.
• They are declared at the point in an application, where they are to be
executed and are passed to PL/SQL engine for execution at runtime.
• It cannot be called.
• There are used in D2K form.
SQL>DECLARE
BEGIN
NULL;
EXCEPTION
WHEN OTHERS THEN
NULL;
END;

266 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Named Block
• The block having name and they have all the features as specified for
the anonymous blocks.
• Named blocks help in associating with the scope and resolution of
variables in different blocks.
• They give the specifications of the named spaces as provided in high
level OOPs languages like C++ and JAVA.
• Named blocks are conveniences for variable management.
SQL><<FirstBlock>>
DECLARE
BEGIN
NULL;
EXCEPTION
WHEN OTHERS THEN
NULL;
END FirstBlock;
• Named blocks make the PL/SQL blocks more clear and readable.
• Named blocks increase the clarity of programming when we attempt
the nesting process, and control structures.
Sub-Programmed blocks
• These are named PL/SQL blocks that can take parameters and can be
invoked with in the other anonymous or sub-programmed PL/SQL
blocks.
• These blocks are either is declared as procedures or functions.
• A procedure block is used for performing an action, and a functional
block is used for performing calculation.
• These sub-programs provides modularity and reusability.

Comments in PL/SQL
• PL/SQL compiler ignores comments.
• Comments promote readability and aids understing.
• PL/SQL supports two types comments
o Single line comments(--)
o /*Multi
Line
Comments */

Variables in PL/SQL
Use of Variables
Variables can be used for:
Temporary storage of data
• Data can be temporarily stored in one or more variables for use
when validating data Input for Processing the Data in the Data flow
process.

267 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Manipulation of stored values


• Information is transmitted between PL/SQL and database with
variables.
• Variables help in the data manipulation of stored values.
• Variables can be used for calculations and others data
manipulations without accessing the database each and every time,
Hence they help in reducing the I/O Cycles.
Reusability
• Once declared can be used repeatedly by even in other blocks.
Ease of maintenance
• Variables can be declared based on the declarations of the
definitions of database columns.
• Provides Data Independence, reduces maintenance costs and
allows programs to adapt the changes as the Database changes.

Handling Variables in PL/SQL


• Declare and initialize variables in the declaration section.
• Declarations allocate storage space for a value according to its
defined size.
• Declarations can be assigned with an Initial value and can be
imposed with a NOT NULL constraint or DEFAULT option.
• We reassign new values to variables in the executable section.
• Pass values into PL/SQL blocks through parameters.
• There are Three parameter modes, They are IN(The default),OUT
and IN OUT.
• View results from a PL/SQL through output of variables.
• Reference variables can be used for Input or Output in SQL data
manipulation statements.

Types of Variables
• PL/SQL variables

– Scalar
– Composite
– Reference
– LOB (large objects)
Scalar Data Types:
• They holds a single value.
• Main data types are those that correspond to column types in
oracle server tables.
• Supports Boolean variables.
Composite Data types:
• A variable of a composite type contains one or more scalar
variables.

268 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

• Composite data types are similar to structures in ‘C’ language.


• They help in keeping all the related data items together as one
collection.
Reference Data types:
• They hold values, acting as pointers, which designate other
program items.
• They are very essential when manipulating collection of data
items in sub programs.
LOB Data types:
• They holds values called locations, specifying the location of
large objects that are stored out of line in the PL/SQL program.
Operators in PL/SQL
• Logical :AND,OR,NOT
• Arithmetic :+,-,*,/
• Concatenation : ||
• Comparison : =,!=,<,>,<=,>=
• SQL*Plus : ISNULL,LIKE,BETWEEN,IN
Assigning values to a variable
• In PL/SQL a variable can be assigned in three ways
• By using assignment operator(:=)
• By selecting or fetching database values(INTO).
• By passing it as IN or OUT or INOUT parameter to a subprogram.
Declaring PL/SQL Variables
Syntax
Identifier name [CONSTANT] datatype [NOT NULL][:=DEFAULT] Expr];
Identifier name
• Specifies the name of the relevant variable for that block.
Constant
• Constant the variable such that its value cannot change during the
program process.
• Constants must be initialized else raise an exception.
Datatype
• It is a scalar, composite, reference of LOB data type as applicable to
the required situation.
NOTNULL
• Constraints a variable such that it must contain a value and raises if
NULL is identified.
• NOT NULL variables should be initialized else raise an exception.

DEFAULT
• Sets the default value for the value in the PL/SQL program if not
attended.

269 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Expr
• It is any PL/SQL expression that can be a literal, another variable or an
expression involving operations and functions for initialization.

Illustration
DECLARE
Vno number(4):=7788;
Vname varchar2(20) not null:=’SCOTT’;
--must not hold null value through out program
Doj date default sysdate;
Flag boolean:= true;
--for boolean variable accept only TRUE or FALSE value and
--value should not be in single code
pcode constant number(6):=567893;
--cannot be used as an assignment target.

Debugging statement
• The debugging statement of PL/SQL is DBMS_OUTPUT.PUT_LINE();
• For producing outputs on the video device we need the assistance of
DBMS_OUTPUT package.
• The package enabled to display output from PL/SQL blocks and sub
programs.
• The procedure PUT_LINE() outputs information to a buffer in the SGA.
• This procedures is used to identify the error during runtime of the
PL/SQL block.
• This procedure requires a single parameter of any of the data types
varchar2 or number or date.
• To see the output of PUT_LINE() on the console of the client side enter
the following SQL plus command on the SQL prompt.

Syntax
DBMS_OUTPUT.PUT_LINE(‘Message’||variablename);
• The DBMS_OUTPUT packages is owned by the oracle user SYS.
• The size of the buffer can be set between 2000 to 10,00,000 bytes.
• The specification to set buffers are
o SET SERVEROUTPUT ON
o SET SERVEROUTPUT ON SIZE 5000
o SET SERVEROUTPUT OFF
SQL>BEGIN
DBMS_OUTPUT.ENABLE;
DBMS_OUTPUT.PUT_LINE('Frist program in PL/SQL');
DBMS_OUTPUT.PUT_LINE('Illustraind by');
DBMS_OUTPUT.PUT_LINE('''Krishna reddy ''');
END;

270 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

• DBMS_OUTPUT.ENABLE; Once declare will make the SERVEROUTPUT


process to get activated.
SQL> DECLARE
V_FirstNum NUMBER:=&fno;
V_SecondNum NUMBER:=&sno;
V_tol NUMBER;
BEGIN
V_tol:=v_FirstNum+V_SecondNum;
DBMS_OUTPUT.PUT_LINE('The sum of Frist and Second num is
'||v_tol);
END;

SQL> BEGIN
DBMS_OUTPUT.PUT_LINE('The sum of Frist and Second num is
'||(&FirstNum+&SecondNum));
END;

Variable Scope and Nested Blocks


Scope:
• The scope of an identifier is that region of a program unit (block,
subprogram, or package) from which you can reference the identifier.
• Once the scope of the variable is lost it means that the life of the
variable no more.
• All variables loose their scope as soon as the PL/SQL block ends or
terminates.
• Oracle automatically release the space upon that variable once its
scope is closed.

Concepts of scoping
• With in the same scope, all identifiers must be unique.
• Even when the data types are differing, variables and parameters
cannot share the same name.
Nested Blocks and variables scope
• PL/SQL blocks can be nested wherever an executable statement is
allowed.
• A nested block becomes a statement.
• An exception section can contain nested blocks.
Scope and visibility diagram
Ex:
DECLARE
x NUMBER;
BEGIN
DECLARE
y NUMBER;

271 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

BEGIN
y:= x;
END;
...
END;
SQL>DECLARE
m NUMBER:=250;
BEGIN
DBMS_OUTPUT.PUT_LINE('The value of Outer m:'||m);
DECLARE
m NUMBER :=550;
BEGIN
DBMS_OUTPUT.PUT_LINE('The value of Outer m:'||m);
END;
DBMS_OUTPUT.PUT_LINE('The value of Outer m:'||m);
END;
SQL> DECLARE
m NUMBER:=100;
BEGIN
m:=200;
DBMS_OUTPUT.PUT_LINE('The value of Outer m:'||m);
DECLARE
n NUMBER :=300;
v_tol NUMBER;
BEGIN
m:=500;
n:=600;
v_tol:=m+n;
DBMS_OUTPUT.PUT_LINE('The sum of m,n is :'||v_tol);
END;
DBMS_OUTPUT.PUT_LINE('The value of Outer m:'||m);
END;
Labeled Block
• Represent blocks with a label associated to them.
How to convert the anonymous block to Label block
• we need to place a label before the DECLARE keyword.
• The label can also can use appear after the END keyword and it is
optional.
• The advantage of of labeled block is that labeled blocks allow you to
access those variables that would not be visible when using
anonymous block.
SQL> <<Block1>>DECLARE
m NUMBER:=100;
BEGIN

272 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

m:=200;
DBMS_OUTPUT.PUT_LINE('The value of Outer m:'||m);
<<block2>>DECLARE
n NUMBER :=300;
v_tol NUMBER;
m number:=400;
BEGIN
block1.m:=500;
n:=600;
v_tol:=block1.m+n;
DBMS_OUTPUT.PUT_LINE('The sum of block1 m,n is :'||v_tol);
DBMS_OUTPUT.PUT_LINE('The value of Inner block is:'||m);
END block2;
DBMS_OUTPUT.PUT_LINE('The value of Outer m:'||m);
END block1;

>CREATE TABLE kcb_acc_tab(


accno VARCHAR2(20) CONSTRAINT pk_accno PRIMARY KEY,
name VARCHAR2(20) CONSTRAINT nn_name NOT NULL,
acctype CHAR CONSTRAINT chk_atype CHECK (acctype IN('C','S','R')),
doo timestamp DEFAULT sysdate,
bal NUMBER(7,2) CONSTRAINT nn_BAL NOT NULL
);

273 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Writing Control Structures


• PL/SQL can also process data using flow of control statements.
• PL/SQL helps us manipulates and process oracle data using control
statements.
• The flow of control statements can be classified under the following
categories:
o Conditional control
o Iterative control
o Sequential control
The statement structures provided by PL/SQL for this purpose are
• IF-THEN-ELSE
• END IF
• ELSIF
• CASE
• END CASE
• LOOP
• FOR-LOOP
• WHILE-LOOP
• END LOOP
• EXIT-WHEN and
• GOTO

• By integration all the above statements in a proper way a PL/SQL


programmer can handle any real time situation.

Conditional Control
• Sequence of statement can be executed based on a certain condition
using the IF statement.
• There are three forms of IF statements
o IF-THEN-END IF
o IF-THEN-ELSE-END IF
o IF-THEN-ELSIF-END IF
General Syntax
IF condition THEN
sequences of statements;
END IF;
Points to Ponder
• IF…THEN is a reserved word and marks the beginning of the “IF”
statement.
• The “END IF” is a reserved phrase that indicates the end of the
“IF…THEN” construct.

274 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

• When “IF…THEN” is executed, A condition is evaluated to either


“TRUE” or “FALSE”.
• Conditions are compared by using either the comparison operators or
SQL*plus operators.
• One “IF” keyword can manage any number of conditions at a point of
time using the LOGICAL CONNECTIVITIES like “AND”,”OR”.
• Even though the multiple conditions need not be constrained by using
brackets, It is better to control their precedence using the proper
implementations of brackets to avoid ambiguity.
• Every “IF” that is implemented needs compulsorily a “TRUE” state
evaluation for its successful execution, But an evaluation state is not
compulsory when the condition is “FALSE”.
• The sequence of statements is executed only if the condition evaluates
to true.
• If it is false or null, then the control passes to the statement after ‘END
IF’.

Sql>BEGIN
IF ascii('A')=65 THEN
DBMS_OUTPUT.PUT_LINE(‘This is true');
END IF;
END;
DECLARE
v_Firstnum NUMBER:=&Fnum;
v_Secondnum NUMBER:=&Snum;
v_Temp NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('Original v_Firstnum='||v_Firstnum);
DBMS_OUTPUT.PUT_LINE('Original
v_Secondnum='||v_Secondnum);
IF v_Firstnum>v_Secondnum THEN
v_Temp:=v_Firstnum;
v_Firstnum:=v_Secondnum;
v_Secondnum:=v_Temp;
END IF;
DBMS_OUTPUT.PUT_LINE('Swapped v_Firstnum=
'||v_Firstnum);
DBMS_OUTPUT.PUT_LINE('Swapped v_Firstnum=
'||v_Secondnum);
END;

275 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

IF…THEN…ELSE…END IF statement

• IF…THEN…ELSE statement enable us to specify two different groups of


statements for execution.
• One group is evaluated when the condition evaluates to “TRUE”, then
next group is evaluated when the condition evaluates to “FALSE”
Syntax
IF condition THEN
sequences of statements;
ELSE
sequences of statements;
END IF;
Sql>DECLARE
v_Firstnum NUMBER:=&Fnum;
v_Secondnum NUMBER:=&Snum;
BEGIN
IF v_Firstnum<v_Secondnum THEN
DBMS_OUTPUT.PUT_LINE(‘Smallest of two number is ‘||v_Firstnum);
ELSE
DBMS_OUTPUT.PUT_LINE(‘Smallest of two number is
‘||v_Secondnum);
END IF;
END;

SQL>DECLARE
v_Num NUMBER:=&Enternumber;
BEGIN
IF MOD(v_Num,2)=0 THEN

DBMS_OUTPUT.PUT_LINE(v_Num||’ is an Even Number.’);


ELSE
DBMS_OUTPUT.PUT_LINE(v_Num||’ is an Odd Number.’);
END IF;
END;

SQL> DECLARE
v_Number1 NUMBER:= &Number1;
v_Number2 NUMBER:= &Number2;
BGEIN
IF v_Number1>v_Number2 THEN
DBMS_OUTPUT.PUT_LINE('The Greatest Number is: '||v_Number1);
ELSE
IF v_Number2>v_Number1 THEN

276 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

DBMS_OUTPUT.PUT_LINE('The Greatest Number is: '||v_Number2);


ELSE
DBMS_OUTPUT.PUT_LINE('The Number are equal '||v_Number1||' and
'||v_Number2);
END IF;
END IF;
END;

Behavior of NULL’s
• In simple “IF” when a condition is evaluated to NULL, then the
statements in “TRUE” state will not be executed, instead the control
will be passed to the first executable statement after the “END IF”.
• In IF…THEN…ELSE construct the FALSE block is executed whenever the
condition evaluates to NULL.
• Hence when ever a conditional process is executed it is better to cross
verify the NULL status of any variable or value before execution.
SQL> DECLARE
v_Firstnum NUMBER:=&Fnum;
v_Secondnum NUMBER:=&Snum;
BEGIN
IF v_Firstnum=v_Secondnum THEN
DBMS_OUTPUT.PUT_LINE('Given numbers are equal');
END IF;
DBMS_OUTPUT.PUT_LINE('Did you watch the NULL effect.');
END;
Note:Supply NULL at runtime to check the affect of NULL
DECLARE
v_num NUMBER:=&Enternumber;
BEGIN
IF MOD(v_num,2)=0 THEN
DBMS_OUTPUT.PUT_LINE(v_num||' is an Even number.');
ELSE
DBMS_OUTPUT.PUT_LINE(v_num||' is an Odd number.');
END IF;
DBMS_OUTPUT.PUT_LINE('Did you watch the Difference...');
END;
Nested “IF” Statements
• The “IF” statements can be nested into one another as per requirements.
• Nested “IF” is a situation in which an “IF” follows another “IF”
immediately for every “TRUE” state of an “IF” condition.
• Each “IF” is considered as an individual block of “IF” and needs proper
nesting.
• Each “IF” block that is opened needs a proper close with “END IF”. Else
PL/SQL raises exceptions.
• Nested “IF” situations have to be planned when we have a series of
conditions fall sequentially.

277 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Syntax:

IF condition THEN

IF condition THEN

IF condition THEN
Statement1;
ELSE

Statement2;

END IF;
ELSE
Statement3;
END IF;
ELSE
Statement4;
END IF;

SQL>DECLARE
v_year NUMBER:=&year;
BEGIN
IF mod(v_year,4)=0 THEN
IF mod(v_year,100)<>0 THEN
DBMS_OUTPUT.PUT_LINE(v_year||' is a leap year');
ELSE
IF mod(v_year,400)=0 THEN
DBMS_OUTPUT.PUT_LINE(v_year||' is a leap year');
ELSE
DBMS_OUTPUT.PUT_LINE(v_year||' is a not a leap year');
END IF;
END IF;
ELSE
DBMS_OUTPUT.PUT_LINE(v_year||' is a not leap year');
END IF;
END;

Branching with Logical connectivity’s


• In this situation one “IF” is associated with a collection of conditions
using either logical either logical “AND” or logical “OR” operator.

278 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Syntax1
IF condition1 AND condition2 THEN
Statement1;
Statement2;
ELSE
Statement1;
Statement2;
END IF;
Syntax2
IF condition1 OR condition2 THEN
Statement1;
Statement2;
ELSE
Statement1;
Statement2;
END IF;
Syntax3
IF condition1 AND condition2 OR Condition3 xTHEN
Statement1;
Statement2;
ELSE
Statement1;
Statement2;
END IF;
ELSIF statements
Syntax:
IF Condition1 THEN
Statements1;
ESLIF Condition2 THEN
Statement2;
ELSIF Condition3 THEN
Statement3;
ELSE
Statement n;
END IF;

SQL>DECLARE
v_TotalEmps NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_TotalEmps
FROM emp;
IF v_TotalEmps=0 THEN
INSERT INTO temp_table values('There are no emps');

279 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

ELSIF v_TotalEmps <5 THEN


INSERT INTO temp_table values('There are few emps joined');
ELSIF v_TotalEmps <10 THEN
INSERT INTO temp_table values('There are little more emps joined');
ELSE
INSERT INTO temp_table values('There are many emps joined');
END IF;
END;
CASE Expressions
• It is similar to a switch statement in C.
• When a particular search condition evaluates to TRUE, the group of
statements associated with this condition are executed.
• We can evaluate conditions using the normal conditional operators or
SQL*Plus operators.
Case expression Syntax
CASE test_var
WHEN value1 THEN
Sequence_of_statements1;
WHEN value2 THEN
Sequence_of_statements2;

WHEN valuen THEN
Sequence_of_statementsn;
[ELSE
else_sequence;]
END CASE;

• The reserved word “CASE” marks the beginning of the CASE


statement.
• The selector is a value that determines, which “WHEN” clause should
be executed.
• Each when clause contains as expression and or more executable
statements associated with it.
• The “ELSE” clause is optional.
• Each “CASE” statement is marked with “END CASE”.
• Where test_var is the variable or expression to be tested, value1
through valuen are the comparison values.
• If none of the values are equal, then else_sequence will be executed.

SQL>DECLARE
v_Dname varchar2(20);
v_Deptno number;
BEGIN
SELECT deptno into v_Deptno

280 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

FROM emp
WHERE empno=&eno;
CASE v_Deptno
WHEN 10 THEN
v_Dname:='ACCOUNTING';
WHEN 20 THEN
v_Dname:='RESEARCH';
WHEN 30 THEN
v_Dname:='SALES';
WHEN 40 THEN
v_Dname:='OPERATIONS';
ELSE
v_Dname:='UNKNOW';
END CASE;
DBMS_OUTPUT.PUT_LINE('Emp dept name is:'||v_Dname);
END;
Labeled CASE statements
• A CASE statement can optionally be labeled, like a PL/SQL block.
• If a CASE statement is labeled, then the label can also appear after the
END CASE clause.
SQL>DECLARE
v_TestVar NUMBER:=10;
BEGIN
<<Mycase>>
CASE v_TestVar
WHEN 10 THEN
DBMS_OUTPUT.PUT_LINE('ACCOUNTING');
WHEN 20 THEN
DBMS_OUTPUT.PUT_LINE('RESEARCH');
WHEN 30 THEN
DBMS_OUTPUT.PUT_LINE('SALES');
WHEN 40 THEN
DBMS_OUTPUT.PUT_LINE('OPERATIONS');
END CASE Mycase;
END;

SQL>Create or replace procedure display(s varchar2)


Is
Begin
Dbms_output.put_line(s);
End;
Loops(Iterations in PL/SQL)
• Loops repeat a statement or sequence of statements multiple times.
• There are three loop types:

281 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

o Basic loop or Simple Loop


o FOR loop
o WHILE loop
Simple Loop
• The most basic kind of loop, simple loops, have the syntax
LOOP
Sequence_of_statemnets;
END LOOP;
• The sequence_of_statements will be executed between the keywords
“LOOP” and “END LOOP”.
• To keep the loop in finite state the “EXIT” statement is used.
• We can add one with the EXIT statement which has the following
syntax:
EXIT [WHEN condition];
EXIT Statement
• “Exit” Statement is used to terminate a LOOP.
• Once the loop is terminated, the control passes to the next statement
after the “END LOOP”.
• The “EXIT” statement should always be placed inside the Loop only.
• “EXIT” can be associate with a “WHEN” clause to allow conditional
termination of the loop.
• The “EXIT” condition can be at the top of the loop or at the end of the
loop as per logical convenience.
• Depending upon the circumstances we can make use of this LOOP as
Pre -Tested loop or Post-Tested loop construct.
• The loop terminates its process when the conditional state is “TRUE”.
• The statement EXIT WHEN condition is equivalent to
IF condition THEN
EXIT;
END IF;
SQL> DECLARE
v_counter Number:=1;
BEGIN
LOOP
INSERT INTO temp_table
VALUES(v_Counter,'Loop index');
v_Counter:=v_Counter+1;
EXIT WHEN v_Counter>50;
END LOOP;
END;

SQL>DECLARE
a Number:=100;
BEGIN

282 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

LOOP
IF a=250 THEN
EXIT;
END IF;

a:=a+25;

display(a);
END LOOP;
END;
Nested Loops:
• It is a situation where one loop is embedded into the other.
• The outer loop and the inner loop get associated with one
another and execute simultaneously.
• The overall loop terminates is dictated by the outer loop’s
“EXIT WHEN “ condition or “EXIT” condition.
• In nested loop’s the outer loops condition evaluated as TRUE,
always makes the inner loop to resume its process and the inner
loop’s termination actually makes the outer loop to update its
process.
SQL> DECLARE
v_num NUMBER:=1;
BEGIN
LOOP
EXIT WHEN v_num>10;
LOOP
EXIT WHEN v_num>5;
display('Inner loop:'||v_num);
v_num:=v_num+1;
END LOOP;
display('Outer loop:'||v_num);
v_num:=v_num+1;
END LOOP;
END;
Nested loops and labels:
• Loops can be nested to multiple levels.
• All the loops can be nested into one another.
• Loops can be labeled as per the requirements.
• Label loops by placing the label before the word loop within the
label delimiters.
• When the loop is labeled, the label name can be optionally
included after the END LOOP statement for clarity.

283 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

DECLARE
v_num NUMBER:=1;
BEGIN
<<outerloop>>LOOP
<<innerloop>>LOOP
EXIT WHEN v_num>5;
display('Inner loop:'||v_num);
v_num:=v_num+1;
END LOOP innerloop;
display('Outer loop:'||v_num);
v_num:=v_num+1;
EXIT WHEN v_num>10;
END LOOP outerloop;
END;
GOTOs and Labels
• The “GOTO” statements allows us to branch to a label unconditionally.
• The label, which is enclosed within double angle brackets must
precede an executable SQL statement or a PL/SQL block.
• When executed, the GOTO statements transfers control to the labeled
statement or block.
Syntax
GOTO LabelName;

Scenario
SQL>CREATE TABLE product_master
(product_no varchar2(6) constraint
pk_product_pk primary key,
Description varchar2(25),
unit_measure varchar2(10),
Qty_on_hand number(8),
reorder_lvl number(8),
cost_price number(10,2),
selling_price number(8,2));

SQL> DECLARE
v_Qtyhand product_master.qty_on_hand%type;
v_Relevel product_master.reorder_lvl%type;
v_product_no product_master.product_no%type;
BEGIN
v_product_no:='&prodno';
SELECT qty_on_hand,reorder_lvl INTO
v_Qtyhand,v_Relevel
FROM product_master

284 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

WHERE product_no=v_product_no;
IF v_Qtyhand<v_Relevel THEN
GOTO updation;
ELSE
GOTO noupdation;
END IF;
<<updation>>
UPDATE product_master SET
qty_on_hand=qty_on_hand+reorder_lvl
WHERE product_no=v_product_no;
RETURN;
<<noupdation>>
display('There are enogh product');
RETURN;
END;
Note:
• Hence to keeps proper meaning within the sequence “RETURN”
should be used..

SQL>DECLARE
v_Counter NUMBER:=1;
BEGIN
LOOP
INSERT INTO temp_table
VALUES(v_Counter,'Loop Count');
v_Counter:=v_Counter+1;
IF v_Counter>=50 THEN
GOTO EndOfLoop;
END IF;
END LOOP;
<<EndOfLoop>>
INSERT INTO temp_table(Ind) VALUES('Done!');
END;
Restrictions on GOTO
• It is illegal to branch into an inner block, loop , or IF statement.
• “GOTO” cannot navigate from the EXCEPTION selection to any other
section of the PL/SQL block.
• “GOTO “ cannot reference a LABLE in a nested block.
• “GOTO” cannot be executed outside an “IF” clause to LABLE inside “IF”
clause.
• It is better to have a limited usage of “GOTO” in programming block.
• “GOTO” cannot navigate from the EXCEPTION selection to any other
section of the PL/SQL block.

285 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

SQL>DECLARE
n NUMBER:=10;
BEGIN
GOTO l_innerblock;
IF n>20 THEN
<<l_innerblock>>
INSERT INTO dept VALUES(50,'SW','HYD');
END IF;
END;

SQL> BEGIN
GOTO l_innerblock;
BEGIN
<<l_innerblock>>
INSERT INTO dept VALUES(50,'SW','HYD');
END;
END;

WHILE Loops
• The WHILE LOOP statement includes a condition associates with a
sequence of statement.
• If the condition evaluates to true, then the sequence of statements will
be executed, and again control resumes at the beginning of the loop.
• IF the condition evaluates to false or NULL, then the loop is bypassed
and the control passes to the next statement.
Syntax
WHILE condition LOOP
statement1; Condition is
statement2; evaluated at the beginning of
... each iteration.
END LOOP;

SQL>DECLARE
n NUMBER(3):=1;
v VARCHAR2(100);
BEGIN
WHILE n<=10
LOOP
v:=v||' '||n;
n:=n+1;
END LOOP;
display(v);
END;

286 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

SQL>DECLARE
n NUMBER(5):=&n;
s NUMBER(5):=0;
r NUMBER(2):=0;
BEGIN
WHILE n!=0
lOOP
r:=mod(n,10);
s:=s+r;
n:=trunc(n/10);
END LOOP;
display('The sum of digit of given number is'||s);
END;

FOR LOOP
• It has the same general structure as the basic loop.
• “FOR LOOP” contains a control statement at the front of the lOOP
keyword, to determine the number of iterations that PL/SQL
performs.
Syntax:
FOR loop_counter IN [REVERSE] Lowerbound..Upperbound
LOOP
Statement1;
Statement2;
END LOOP
Counter:
• It is an implicitly declared INTEGER whose value is automatically
increased or decreased by 1 on each iteration of the LOOP until the
upper bound or lower bound is reached.

Reverse:
• It is a keyword, and causes the counter to decrement with each
iteration from the upper bound to the lower bound.
• The loop_counter need not be declared, as it is implicitly declared
as an integer.
• The bounds of the loop are evaluated once.
• This determines the total number of iterations that loop_counter
will take on the values ranging from low_bound to high_bound,
incrementing by 1 each time until the loop is complete.

DECLARE
v_FactNum NUMBER:=&No;
v_Factorial NUMBER:=1;

287 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

BEGIN
FOR v_Counter IN REVERSE 1..v_FactNum
LOOP
v_Factorial:=v_Factorial*v_Counter;
END LOOP;
DBMS_OUTPUT.PUT_LINE('The Factorial of '||v_FactNum||' is
:'||v_Factorial);
END;

SQL>DECLARE
J NUMBER(2):=&J;
v VARCHAR2(100);
k NUMBER(3);
BEGIN
FOR i in 1..10
loop
k:=j*i;
v:=v||j||'*'||i||'='||k||' ';
end loop;
display(v);
END;
Nested FOR loops
SQL>DECLARE
n NUMBER:=&no;
v VARCHAR2(100);
BEGIN
FOR i IN 1..n
LOOP
FOR k IN 1..i
LOOP
v:=v||' '||k;
END LOOP;
display(v);
v:=null;
END LOOP;
END;

288 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

CURSOR MANAGEMENT
• In order to process a SQL statements, Oracle will allocate an area of
memory know as the context area.
• PL/SQL uses this context area to store and to execute the SQL
statements.
• The information(rows) retrieved from database table, which is
available in context area, is known ‘Active Set’.
• A Cursor is a pointer, which works on active set i.e., which points one
row at a time in the context area.
• A cursor is used to process multiple rows using PL/SQL.

Types of Cursors
• There are two types of cursors
o Implicit cursors
o Explicit cursors
Implicit cursors
• It is a CURSOR that is automatically declared by Oracle every time an
SQL statement is executed.
• These are created or erased automatically.
• These are identified by SQL%<cursor attribute>
• Whenever you issue a SQL statement, the Oracle server opens an area
of memory in which the command is parsed and executed. This area is
called a cursor.
• When the executable part of a block issues a SQL statement, PL/SQL
creates an implicit cursor, which PL/SQL manages automatically.
• A CURSOR is automatically associated with every DML statement.
• All UPDATE and DELETE statements have cursors that identify the set
of rows that will be affected by the operations.
• During processing of an IMPLICIT cursor, oracle automatically
performs the operations like “OPEN”,”FETCH”, and “CLOSE” of the
context area.
Explicit Cursor
• Explicit cursors are explicitly declared by the programmer.
• This cursor is declared within the PL/SQL block, and allows sequential
process of each row of the returned data from database.

Cursor Attributes
• There are four attributes available in PL/SQL that can be applied to
cursor.
• Cursor attributes are appended to a cursor name in a PL/SQL block,
similar to %TYPE and %ROWTYPE.
• The attributes are
o %FOUND

289 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

o %NOTFOUND
o %ISOPEN
o %ROWCOUNT
%FOUND
• Boolean attribute that evaluates to TRUE If the most recent SQL
statement affects one or more rows.
%NOTFOUND
• Boolean attribute that evaluates to TRUE if the most recent SQL
statement does not affect any rows.
%ISOPEN
• Boolean attribute that evaluates to TRUE if the cursor is open else
evaluates to FALSE.
%ROWCOUNT
• Number of rows affected by the most recent SQL statement (an integer
value).

SQL>var rows_deleted varchar2(20)


SQL>DECLARE
v_Empno emp.empno%TYPE := 7788;
BEGIN
DELETE FROM emp
WHERE empno = v_Empno;
:rows_deleted:= (SQL%ROWCOUNT ||' row deleted.');
END;
SQL> DECLARE
v_Job Emp.Job%TYPE:='&Job';
BEGIN
UPDATE emp
SET sal=sal+1000
WHERE job=v_Job;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||'Rows were Updated.');
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('Data Not Found So, No updation.');
END IF;
END;

Implicit FOR Loops


SQL>DECLARE
FOR v_Empdata IN(SELECT ename,job,sal,comm
FROM emp
WHERE deptno=30)
LOOP
INSERT INTO bonus
VALUES(v_Empdata.ename,v_Empdata.job,v_Empdata.sal,

290 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

v_Empdata.comm);
END LOOP;
END;

Explicit Cursor
• An EXPLICT CURSOR is generated using a name with association of
select statement in the DECLARE section of the PL/SQL block.
Advantages
• Explicit cursor provide more programmatic control for programmers.
• Explicit cursor are more efficient in implementation, hence easy to
trap errors.
How cursor will work
The life cycle of the explicit cursor goes through four stages.
DECALRE
OPEN
FETCH
CLOSE
DECLARE:
• The CURSOR is declared in the declarative block and is provided with a
name and a SELECT statement.
Syntax:-
CURSOR <cursor name is
Select_statement.

Note:-in <select statement> include most of the usual


clauses, except INTO clause.(if use It there is no use).
• The cursor name can be any valid identifier.
• Any SELECT statements are legal, including joins and statements with
the SET OPERATORS.

Illustration
>declare
vsal number:=2000;
cursor c1 is
select sal into vsal
from emp
where empno=7902;
begin
display('The vsal val is '||vsal);
end;

291 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Opening a Cursor:
Syntax:
OPEN cursor_name;

• The opening of cursor executes the query and retrieves the


information from the database and dumps it into the context area to
foam active set.
• Cursor can be opened only in the EXECUTION OR EXCEPTION section
of the PL/SQL block.
• The active set pointer is set to the first row.
• Once a cursor has been opened, it cannot be reopened unless it is first
closed.
Fetching from a Cursor
• Fetch the record from CONTEXT AREA into cursor variable.
• This fetches 1 row at a time into the cursor variable from the active
set.
• The INTO clause for the query is part of the FETCH statement.

The FETCH statement has two forms:

Syntax:
1) FETCH cursor_name INTO list_of_variables;
2) FETCH cursor_name INTO PL/SQL_record;

• The list_of_variable is a comma-separated list of previously


declared PL/SQL variable, and PL/SQL_record is a previously
declared PL/SQL record.
Illustration:
FETCH Empcursor INTO v_emprecord;
Closing a Cursor
• This tells PL/SQL engine that the program is finished with the
cursor, and the resources associated with it can be freed.
• These resource include the storage used to hold the active set,
as well as any temporary space used for determining the active
set.
• The active set can be re-established several times.
Syntax
CLOSE <cursor name>;
Cursor Attributes
• There are four attributes available in PL/SQL that can be applied to
cursors. cursor attributes are appended to a cursor name in PL/SQL
block and then used in expressions.
• The attributes are
1) <cursor name>%Found

292 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

2) <cursor name>%NotFound
3) <cursor name>%ISOPEN
4) <cursor name>%Rowcount

Active Set:
The set of rows returned by a multiple-row query is called the Active Set.

Private SQL Area


Select
statement
Active set

Cursor Current Row


Further Rows

SQL>declare
cursor c1 is
select empno,ename,sal
from emp
where deptno=20;
vempno emp.empno%type;
vename emp.ename%type;
vsal emp.sal%type;
begin
open c1;
loop
fetch c1 into vempno,vename,vsal;
exit when c1%notfound;
if vsal between 0 and 1000 then
vsal:=vsal+vsal*0.15;
elsif vsal between 1001 and 2000 then
vsal:=vsal+vsal*0.25;
else
vsal:=vsal+vsal*0.35;
end if;

293 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

update emp set sal=vsal


where empno=vempno;
display(rpad(vename,8)||' '||vsal);
end loop;
close c1;
end;
SQL>declare
cursor jc is
select empno,ename,job,sal
from emp;
i emp%rowtype;
begin
open jc;
loop
fetch jc into i.empno,i.ename,i.job,i.sal;
exit when jc%notfound;
if i.job='CLERK' then
i.sal:=i.sal+100;
elsif i.job='SALESMAN' then
i.sal:=i.sal+200;
else
i.sal:=i.sal+300;
end if;
update emp set sal=i.sal
where empno=i.empno;
display(rpad(i.ename,8)||' '||rpad(i.job,10)||' '||i.sal);
end loop;
close jc;
end;
>declare
cursor cc is
select empno,ename,comm
from emp;
i cc%rowtype;
begin
open cc;
loop
fetch cc into i;
exit when cc%notfound;
if i.comm is null then
i.comm:=300;
elsif i.comm=0 then
i.comm:=250;
else

294 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

i.comm:=i.comm+i.comm*0.35;
end if;
update emp set comm=i.comm
where empno=i.empno;
display(rpad(i.ename,8)||' '||i.comm);
end loop;
close cc;
end;
SQL>declare
cursor cpf is
select empno,ename,sal basic,sal*0.45 hra,sal*0.35 da,sal*0.15 pf,deptno
from emp
where sal>4000;
i cpf%rowtype;
vgross number;
begin
open cpf;
loop
fetch cpf into i;
if cpf%found then
vgross:=i.basic+i.hra+i.da-i.pf;
display(i.empno||' '||rpad(i.ename,8)||' '||rpad(i.basic,6)||'
'||rpad(i.hra,5)||' '||
rpad(i.da,5)||' '||rpad(i.pf,5)||' '||
rpad(vgross,5)||' '||i.deptno);
else
exit;
end if;
end loop;
display('No of emps eligible for pf is'||cpf%rowcount);
close cpf;
end;
> insert into utab
values(upper('&uid'),
Translate( upper('&password'),
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'1234567890!@#$%^&*()-=_+;,.')
);

SQL>declare
cursor primary_cur is
select 'X'
from utab
where userid=upper('&uid') and

295 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

password=Translate(upper('&password'),
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'1234567890!@#$%^&*()-=_+;,.');

dummy_var char;
begin
open primary_cur;
fetch primary_cur into dummy_var;
if primary_cur%found then
display('The userid and password corr');
else
display('Unknow userid and password');
end if;
close primary_cur;
end;
Cursor with For loops
• PL/SQL provides a simple type of loop, which implicitly handles the
cursor processing.
• Within the loop each record in the Active set is retrieved and used.
• Each loop iteration advances the cursor pointer by one record in the
Active set.
• The loop works on the range oriented operational logic.
• The loop is very useful when traveling the entire data in the database
table.
• It is more Dynamic in operation than the Simple loop.
Syntax
For <variable> IN <cursor name>
LOOP
<Ex Stmt>;
END LOOP;

Advantages
No need to
→Declare INDEX variable explicitly.
→OPEN a cursor .
→FETCH the rows from cursor.
→Terminate the loop explicitly.
→CLOSE the cursor.
SQL>declare
cursor cpf is
select empno,ename,sal basic,sal*0.45 hra,sal*0.35 da,sal*0.15 pf,deptno
from emp
where sal>4000;
vgross number;

296 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

cnt number;
begin
for i in cpf
loop
vgross:=i.basic+i.hra+i.da-i.pf;
display(i.empno||' '||rpad(i.ename,8)||' '||rpad(i.basic,6)||'
'||rpad(i.hra,5)||' '||
rpad(i.da,5)||' '||rpad(i.pf,5)||' '||rpad(vgross,5)||' '||i.deptno);
cnt:=cpf%rowcount;
end loop;
display('No of emps eligible for pf is'||cnt);
end;
parametric Cursor
• The cursor defined with parameter is called parametric Cursor.
• Cursor parameters can be assigned with default values.
• The Mode of cursor parameters can be only “IN” Mode.
Syntax
CURSOR Cursorname(ParameterName Datatype,…)
IS
SELECT statement;
Illustration
SQL> DECLARE
CURSOR Empcursor
(Pdeptno NUMBER,
Pjob VARCHAR2) IS
SELECT empno, ename
FROM emp
WHERE deptno = Pdeptno AND job = Pjob;
Methods of Opening a Parametric Cursor
1.Open Empcursor(30,’SALESMAN’);
2.DECLARE
v_empdeptno Emp.deptno%TYPE:=&Givedeptno;
v_empjob Emp.job%TYPE:=&GiveJob;
BEGIN
OPEN Empcursor(v_empdeptno,v_empjob);
3. DECLARE
CURSOR Empcursor
(Pdeptno NUMBER,
Pjob VARCHAR2) IS
SELECT empno, ename
FROM emp
WHERE deptno = Pdeptno AND job = Pjob;
BEGIN
FOR Emprecord IN Empcursor(20,’CLERK’)

297 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

LOOP
Import Points
• Unless you want to accept default values, each formal parameter in
the cursor declaration must have a corresponding actual parameter in
the OPEN statement.
• A parametric cursor can be opened and closed explicitly several times
in a PL/SQL Block.
• A parametric cursor returns a different Active Set on each occasion.
• The concept is more useful when the same Cursor is Referenced
repeatedly.

SQL>declare
cursor dc is
select deptno
from dept;
cursor ec(pdno in dept.deptno%type)
is
select empno,ename,sal basic,sal*0.45 hra,
sal*0.35 da,sal*0.15 pf,deptno
from emp
where deptno=pdno;
vdno dept.deptno%type;
i ec%rowtype;
vgross number;
begin
open dc;
loop
fetch dc into vdno;
exit when dc%notfound;
open ec(vdno);
loop
fetch ec into i;
exit when ec%notfound;
vgross:=i.basic+i.hra+i.da-i.pf;
display(i.empno||' '||rpad(i.ename,8)||' '||rpad(i.basic,5)||'
'||rpad(i.hra,5)||' '||
rpad(i.da,5)||' '||rpad(i.pf,5)||' '||
rpad(vgross,5)||' '||i.deptno);
end loop;
if ec%rowcount>0 then
display('-----------------------------------------------------');
end if;
close ec;

298 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

end loop;
end;
SQL> declare
cursor dc is
select unique deptno
from emp;
cursor ec(pdno in emp.deptno%type)
is
select empno,ename,sal basic,sal*0.45 hra,
sal*0.35 da,sal*0.15 pf,deptno
from emp
where deptno=pdno;
vdno emp.deptno%type;
i ec%rowtype;
vgross number;
begin
delete from emp_report;
open dc;
loop
fetch dc into vdno;
exit when dc%notfound;
open ec(vdno);
loop
fetch ec into i;
exit when ec%notfound;
vgross:=i.basic+i.hra+i.da-i.pf;
insert into emp_report values(i.empno,i.ename,i.basic,i.hra,i.da,i.pf,vgross,
i.deptno);
end loop;
if ec%rowcount>0 then
insert into emp_report(ecode) values(null);
end if;
close ec;
end loop;
end;

FOR UPDATE Clause


• FOR UPDATE clause explicitly locks the records Stored in the private
work area.
• The FOR UPDATE clause in the cursor query is used to LOCK the
affected rows while the cursor is opened.
• You need not need provide an explicit COMMIT command to release
the lock acquired by using the FOR UPDATE clause.

299 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Using WHERE CURRENT OF clause


• WHERE CURRENT OF clause to refer the current record, fetched from
the
explicit cursor.
• we need to suffix the name of the explicit cursor with the CURRENT
OF clause to refer to current record.
• In order to use the WHER CURRENT OF clause, you need to lock the
record
fetched from the cursor.

SQL>declare
cursor lc is
select ename,sal,deptno
from emp
for update;
i lc%rowtype;
begin
display('The emp det are');
display('EmpName'||' '||'Salary'||' '||'DeptNum');
display('-------'||' '||'------'||' '||'-------');
open lc;
loop
fetch lc into i;
exit when lc%notfound;
display(rpad(i.ename,8)||' '||rpad(i.sal,5)||' '||i.deptno);
if i.deptno=50 then
delete from emp
where current of lc;
end if;
end loop;
close lc;
display('After delete the 50th dept emps');
open lc;
loop
fetch lc into i;
exit when lc%notfound;
display(rpad(i.ename,8)||' '||rpad(i.sal,5)||' '||i.deptno);
end loop;
close lc;
end;

300 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Cursors with sub Queries


• A CURSOR can be constructed upon the result provided through a
SUBQUERY.
• The sub query can be an ordinary one or a correlated sub query.

SQL>DECLARE
CURSOR cs is
SELECT d.deptno,d.dname,d.loc,v.noe
FROM dept d,(SELECT deptno,count(*) noe
FROM emp
group by deptno) v
WHERE v.noe>3 AND
d.deptno=v.deptno;
BEGIN
FOR i in cs
LOOP
display(i.deptno||' '||i.dname||' '||i.loc||' '||i.noe);
END LOOP;
END;

Dynamic Cursor Ref Cursor or Cursor Variable


• Explicit cursor is Static Cursor.
• Explicit cursor referrers always one work area associated with
cursor.
• Dynamic cursor is Ref Cursor, It referrers different work area in
memory.
• Cursor variables are analogous to PL/SQL variables, which can hold
different values at runtime.
• It is used to declare a cursor with out select statement.
• A Ref Cursor can be reused if it is declared in package.
• A Ref Cursor support to return more than 1 row from sub program.
• Deferent select statement can be associated with cursor variable at
run time.
Types of cursor variable
• There are two types of Ref Cursor.
weak cursor variable or Weak Ref Cursor
• If we do not include a RETURN clause in the Cursor, then it is a
weak REF Cursor.
• Cursor variables declared from weak REF cursors can be associated
with any query at runtime.

301 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Syntax:
step1:
Type <type name> is ref cursor;

step2:
<cursor variable name> <type name>;

step3:
open<cursor variable name>
for(select statement);
fetch
exit
close;

strong cursor variable


• A REF CURSOR with a RETUN clause define a “Strong” REF
CURSOR.

Syntax:
step1:
Type <type name> is ref cursor
RETURN record_type;

step2:
<cursor variable name> <type name>;

step3:
open<cursor variable name>
for(select statement);
fetch
exit
close;
SQL>DECLARE
vempno emp.empno%type;
vename emp.ename%type;
vsal emp.sal%type;
vjob emp.job%type;
vdeptno emp.deptno%type;
TYPE ref_c IS REF CURSOR;
c1 ref_c; --it is data type of ref_c
begin
vdeptno:=&dno;
IF vdeptno=10 THEN
OPEN c1 FOR SELECT empno,ename,sal

302 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

FROM EMP WHERE deptno=vdeptno;


ELSIF vdeptno=20 THEN
OPEN c1 FOR SELECT ename,job,sal
FROM emp WHERE deptno=vdeptno;
ELSE
OPEN c1 FOR SELECT ename,sal,deptno
FROM emp
WHERE deptno=vdeptno;
END IF;
IF vdeptno=10 THEN
LOOP
FETCH c1 INTO vempno,vename,vsal;
EXIT WHEN C1%NOTFOUND;
display(vempno||' '||vename||' '||vsal);
END LOOP;
CLOSE c1;
ELSIF vdeptno=20 THEN
LOOP
FETCH c1 INTO vename,vjob,vsal;
EXIT WHEN C1%NOTFOUND;
display(vename||' '||vjob||' '||vsal);
END LOOP;
CLOSE c1;
ELSE
LOOP
FETCH c1 INTO vename,vsal,vdeptno;
EXIT WHEN c1%NOTFOUND;
display(vename||' '||vsal||' '||vdeptno);
END LOOP;
END IF;
END;

303 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Exception Handling
• An Exception in PL /SQL Block is Raised during Execution of a Block.
• Once an EXCEPTION arises it terminates the main body of actions
performed by the PL/SQL block.
• A Block always terminates when PL / SQL Raises an Exception.
• WE can specify an exception handler to perform
• Final action.
Note :
• If the exception is raised in the executable section of the Block and
there is no corresponding Handler, the PL / SQL Block
Terminates with Failure.
• If the exception is handled then PL / SQL Block terminates
successfully.
Exception Handling
• An Exception is raised when an error occurs.
• In case of an error, normal exception stops and the control is
immediately transferred to the exception handling part of the PL/SQL
block.

Trapping Exceptions
• The exception handling section consists of handlers for all the exceptions.
• An exception handler contains the code that is executed when the error
associated with the exception occurs, and the exception raised.
• Each exception handler consists of a WHEN clause which specifies an
EXCEPTION that has to be handled.
Syntax
Exception
When <exception1> [or exception2…] Then
SQL statement1
SQL statement2
When <exception3> [or exception4…] Then
SQL statement1
SQL statement2
When Others Then
SQL statement1
SQL statement2
End;
The Others Exception Handler
• The OTHERS exception is an optional EXCEPTION handling clause
that traps unspecified exceptions.
• The OTHERS should always be the last handler in the block.

304 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

• It is good programming practice to have an OTHERS handler at the


top level of your program to ensure that no errors go undetected.
Exception Guidelines
• Begin the EXCEPTION handling section of the block with the keywords
EXCEPTION.
• Define several EXCEPTION HANDLERS ,each with its own set of action
for the block.
• Avoiding unhandled exceptions, this can be done via an OTHERS
handler at the topmost level program.
• When an EXCEPTION occurs PL/SQL processes only one handle before
leaving the block.
Predefined Exception
• Oracle has predefined several exceptions that correspond to the most
common oracle errors.
• A predefined oracle server error is trapped by referencing its standard
name within the corresponding exception handling at runtime.
• Each Predefined Exception begins With ORA followed by a number.
• As soon As the Exception occurs oracle implicitly raise the exception
and jumps into the EXCEPTION handle block, if proper EXCEPTION
handle is found manages the specified steps.
• In predefined oracle server exceptions only one exception is raised and
handled at any time.

Types of Exception

Pre defined(System defined)


• Predefined exception are raised automatically by the system during
run time.
• Predefined exception are already available in the program it is not
necessary to declare them in the declarative section like user_defined
exception.

Predefined Exception List

Exception Name Error No Description


ORA-0001 DUP_VAL_ON_INDEX Unique constraint violated.
ORA-1001 INVALID_CURSOR Illegal Cursor operation.
ORA-1403 NO_DATA_FOUND No data found.
ORA-1422 TOO_MANY_ROWS A SELECT…INTO statement
matches more than one row.

ORA-1722 INVALID_NUMBER Conversion to a number failed


For example,’krishna street 1’
not valid.
ORA-6502 VALUE_ERROR Truncation, arithmetic, or

305 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT
conversion error.
ORA-01476 ZERO_DIVIDE Divisor is equal to zero
ORA-06511 CURSOR_ALREADY_OPEN This exception is raised when
We try to open a cursor which is
already opened.
ORA-01017 LOGIN_DENIED This exception is raised when we
try to enter oracle using invalid
username/password.

>DECLARE
v_empno emp.empno%TYPE:=&empno;
v_ename emp.ename%TYPE;
v_job emp.job%TYPE;
BEGIN
SELECT ename,job INTO v_ename,v_job
FROM emp
WHERE empno=v_empno;
DBMS_OUTPUT.PUT_LINE('The empno detail are '||v_ename||'
'||v_job);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('The empno is not found.');
END;

SQL>DECLARE
v_accno kcb_acc_tab.accno%TYPE:=&accno;
v_name kcb_acc_tab.name%TYPE:='&name';
v_bal kcb_acc_tab.bal%TYPE:=&bal;
BEGIN
INSERT INTO kcb_acc_tab(accno,name,bal)
VALUES(v_accno,v_name,v_bal);
DBMS_OUTPUT.PUT_LINE('Account detailes are inserted
successfully.');
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('accno already exists');
END;
SQL> DECLARE
v_empno emp.empno%TYPE;
v_ename emp.ename%TYPE;
v_deptno emp.deptno%TYPE;

306 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

BEGIN
SELECT empno,ename,deptno INTO v_empno,v_ename,v_deptno
FROM emp
WHERE empno=7788 AND ename='SCOTT';
DBMS_OUTPUT.PUT_LINE('The scott works in department
number:'||v_deptno);
Select empno,ename,deptno into v_empno,v_ename,v_deptno
FROM emp
Where deptno=10;
DBMS_OUTPUT.PUT_LINE('The Employee number:'||v_empno);
DBMS_OUTPUT.PUT_LINE('The Employee name:'||v_ename);
Exception
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Error:There is no such empno or
ename or deptno');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Error:More than one Employee works
in department number 10');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error occurred while processing the
program');
END;

User-defined Exception:
• A user-defined exception is an error that is defined by the
program
• The developers to handle the business situations define user-
defined exceptions during the execution of the PL/SQL block.
• User defined exceptions are defined by the following two
techniques:

→Using a flow control statement RAISE


Raise statement transfer the control of the block from the
execution part of the PL/SQL block to the exception handing part
of the block.

Step
1. Declare Exception

2. Raise in Executable section explicitly


using
RAISE <Exception_handler_name>;

3. Handle the raised exception

307 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

→Using a packaged procedure


RAISE_APPLICATION_ERROR(error number,’Error
message’);
RAISE_APPLICATION_ERROR
• This Built-in procedure is used to create your own error message,
which can be more descriptive than named exceptions.
• It is used to communicate a predefined exception interactively by
returning a non standard error code and error message.
• Using this procedure we can report error to application and avoid
returning unhandled exception.
Note:
• Error number must exists between -20,000 and -20,999
• Error_message is the text associate with this error, and keep_errors is
Boolean value.
• The error_message parameter must be less than 512 characters.
SQLCODE FUNCTION
• It returns the current error code.
• For a user defined exception it returns 1, +100
NO_DATA_FOUND exception.
SQLERRM
• It returns the current error message text.
• SQLERRM returns the message associated with the error number.
• The maximum length of a message returned by the SQLERRM
functions is 512 bytes.

SQL> DECLARE
i emp%rowtype;
BEGIN
i.empno:=&eno;
SELECT ename,sal into i.ename,i.sal
from emp
where empno=i.empno;
IF i.sal<2000 THEN
Raise_application_error(-20345,'The emp sal is less than 2000 so no
updation');
i.sal:=i.sal+i.sal*0.35;
UPDATE emp set sal=i.sal
WHERE empno=i.empno;
ELSE
i.sal:=i.sal+i.sal*0.35;
UPDATE emp set sal=i.sal
WHERE empno=i.empno;
display('The emp det are '||i.ename||' '||i.sal);

308 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

END IF;
END;

QL>DECLARE
salary_missing EXCEPTION;
i emp%rowtype;
BEGIN
i.empno:=&eno;
SELECT ename,sal into i.ename,i.sal
FROM emp
WHERE empno=i.empno;
IF i.sal IS NULL THEN
RAISE salary_missing;
ELSE
i.sal:=i.sal+i.sal*0.25;
UPDATE emp SET sal=i.sal
WHERE empno=i.empno;
display('The emp det are '||i.ename||' '||i.sal);
END IF;
EXCEPTION
WHEN no_data_found THEN
display(i.empno||' is not exists');
display(SQLCODE||' '||SQLERRM);
WHEN salary_missing THEN
display('The emp is not having any salary so give salary as 3000');
UPDATE emp SET sal=i.sal
WHERE empno=i.empno;
display(SQLCODE||' '||SQLERRM);
WHEN others then
display('The SUHE');
END;
Trapping Non-Predefined oracle server errors
• We can associate a named exception with a particular oracle error.
• The Non-predefined oracle server error is trapped by declaring it first
or by using the OTHERS exception handle.
• The declare EXCEPTION is RAISED implicitly by the oracle server.
• The PL/SQL PRAGMA EXCEPTION_INIT() can be used for associating
EXCEPTION name with an oracle error number.
• The PRAGMA EXCEPTION_INIT() tells the PL/SQL engine completely to
associate an EXCEPTION name with an oracle error number.
• The PRAGMA EXCEPTION_INIT() allows programmer to refer to any
internal EXCEPTION by the name and associate that to specific
handles.

309 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

• Pragma is a directive of compiler which tells compiler to associate error


no with user declared exception at compile time.
Steps
1.Declare Exception

2. Associate Exception with Oracle error No.


Using
Pragma
exception_init(exception_name,oracle_error_number);
3. Handle the raised exception

• Exeption_name is the name of an exception declare prior to the


pragma.
• Oracle _erroe_number is the desied error code to be associate with
this named exception.
SQL> DECLARE
pk_vio EXCEPTION;
PRAGMA EXCEPTION_INIT(pk_vio,-00001);
BEGIN
insert into emp(empno,ename,sal,deptno)
values(&eno,'&ename',&sal,&deptno);
EXCEPTION
when pk_vio then
dbms_output.put_line('Duplicate empno is not allowed here');
END;

Understanding PL/SQL Collections

• PL/SQL , similar to other programming languages such as C,C++,


allows using arrays and records.
• PL/SQL has two composite types :records and collections.
PL/SQL Records
• A PL/SQL Record is allows you to treat several variables as a unit.
• PL/SQL Record are similar to structure in C.
• When a “RECORD TYPE” of fields are declared then they can be
manipulated as a Unit through out the Application.
Note:
• In the composite data type RECORD, we can specify the data type of the column.
• Each RECORD defined can have as many Fields as necessary.
• Fields declared as ‘not null’ must be initialized in the declaration part.

310 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

• A record can be initialized in its declaration part unlike PL/SQL tables, which doesn’t
allow initialization in the declaration part.
• The DEFAULT key word can also be used when defining fields.
• A RECORD can be the component of another RECORD.
Syntax

TYPE type_name IS RECORD


(Element1 <data type>,
Element2 <data type>,
Element3 <data type>,
Element4 <data type>,
Elementn <data type>);

• field_declaration syntax is
Elementname{ Elementdatatype(size) OR
Recordvariable%TYPE OR
Table.column%TYPE OR
Table%ROWTYPE}
[[NOT NULL] {:= OR DEFAULT} expr]
Defining PL/SQL Record

• To define a user defined PL/SQL data type


o Type name→is the name of the Record type.
o Element name→It is the name of the field within the Record.
o Element Data Type→It is the data type of the Element.
o Expr →It is the Field type OR an Initial Value.
o
→The NOT NULL constraint prevents the Assigning of NULL’s to those Fields.
→Element declaration are like variable declaration each Element has a unique name and
A specific data type.
→We must create the data type first and then declare an identifier using the declared data
type.

Illustration
SQL>DECLARE
TYPE erec IS RECORD
(veno NUMBER(4),
vname emp.ename%TYPE,
basic emp.sal%TYPE,
i dept%ROWTYPE,
vgross number(16,2));
e erec;
BEGIN
e.veno:=&employe;

311 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

select ename,sal,dept.deptno,dname into


e.vname,e.basic,e.i.deptno,e.i.dname
from emp,dept
where emp.deptno=dept.deptno and empno=e.veno;
e.vgross:=e.basic+e.basic*.25+e.basic*.35-e.basic*.12;
display(e.veno||' '||e.basic||' '||e.i.deptno||' '||e.i.dname||' '||e.vgross);
END;

PL/SQL Tables
• PL/SQL tables are temporary array-like objects used in a PL/SQL block.
• They are modeled as database tables, but are not same.
• PL/SQL tables are very dynamic in operation, giving the simulation to pointers in ‘C’
language.
• PL/SQL TABLES use a “PRIMARY KEY” to give array like access to rows.
• PL/SQL table can be declared in the declarative part of any block. Subprogram or
package.
• It is similar to an array in Third generation language.
• PL/SQL table should contain two components.
o A “PRIMARY KEY” of data type BINARY_INTEGER, that indexes the PL/SQL
table.
o A column of a scalar or Record data type which stores the PL/SQL table
elements.

• PL/SQL tables can increase in size dynamically as they are unconstrainted.


• A PL/SQL TABLE must be declare in two steps.

1) First we define a table type


2)We declare a variable of PL/SQL table as data type.

Syntax
TYPE <Type name> IS TABLE OF
{column type OR Table.column%TYPE OR PL/SQL RECORD}
INDEX BY BINARY_INTEGER;

• The number of rows in PL/SQL table can increase dynamically, hence a PL/SQL table
can grow as new rows are added.
Referencing PL/SQL Table
• PLSQL_Tablename(Primary_key_value);
• PRIMARY_KEY_VALUE belongs to type BINARY_INTEGER.
• The primary key value can be negative indexing need not start with 1.
• The method make PL/SQL tables easier to use are.
COUNT
• Returns the number of elements that a PL/SQL table currently contais.
SQL>DECLARE

312 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

TYPE name IS TABLE OF


VARCHAR2(50) INDEX BY BINARY_INTEGER;
n name;
BEGIN
n(0):='Siva';
n(1):='Rama';
n(2):='Krishna';
display('The full name is '||n(0)||' '||n(1)||' '||n(2));
END;

Note: In oracle 11g Negative index are not allowed.

Trace table:
---------------
ename varchar2(20),
usal number(7,2),
dou timestamp

SQL>DECLARE
TYPE eno IS TABLE OF
emp.empno%TYPE INDEX BY BINARY_INTEGER;
TYPE name IS TABLE OF
emp.ename%TYPE INDEX BY BINARY_INTEGER;
TYPE pays IS TABLE OF
emp.sal%TYPE INDEX BY BINARY_INTEGER;
e eno;
n name;
p pays;
ctl number:=1;
BEGIN
FOR i IN(SELECT empno,ename,sal FROM emp)
LOOP
e(ctl):=i.empno;
n(ctl):=i.ename;
p(ctl):=i.sal;
ctl:=ctl+1;
END LOOP;
for MyIndex IN 1..e.count
LOOP
IF p(MyIndex) BETWEEN 0 AND 1000 THEN
p(MyIndex):=p(MyIndex)+100;
ELSIF p(MyIndex) BETWEEN 1001 AND 2000 THEN
p(MyIndex):=p(MyIndex)+200;
ELSE
p(MyIndex):=p(MyIndex)+300;
END IF;

313 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

UPDATE emp SET sal=p(MyIndex)


WHERE empno=e(MyIndex);
INSERT INTO trace VALUES(n(MyIndex),p(MyIndex),sysdate);
Display(n(MyIndex)||' '||p(MyIndex));
END LOOP;
END;
Nested type Collection
TYPE type_name IS RECORD
(
EmpRecord Emp%ROWTYPE,
DeptRecord Dept%ROWTYPE,
Element RECORD);

SQL>DECLARE
TYPE pf_info is RECORD
(pfno NUMBER(4),
amount NUMBER(14,2));
TYPE emp_rec IS RECORD
(eid NUMBER(4),
name VARCHAR2(20),
basic NUMBER(12,2),
pf pf_info);
TYPE etab IS TABLE OF emp_rec
INDEX BY BINARY_INTEGER;
ctr NUMBER(3):=1;
e etab;
BEGIN
FOR i IN(SELECT empno,ename,sal basic,
sal*.12 pamt FROM emp
WHERE sal>2000)
LOOP
e(ctr).eid:=i.empno;
e(ctr).name:=i.ename;
e(ctr).basic:=i.basic;
e(ctr).pf.pfno:=i.empno+5;
e(ctr).pf.amount:=i.pamt;
ctr:=ctr+1;
END LOOP;
display('employee detailes are:');
FOR MyIndex in 1..e.count
loop
display(e(MyIndex).eid||' ‘‘||e(MyIndex).name||'
'||e(MyIndex).basic||' '||e(MyIndex).pf.pfno||'
'||e(MyIndex).pf.amount);
END LOOP;
END;

314 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

RETURNING Clause
• This clause is valid at the end of any DML statement.
• It is used to get information about the row or rows just processed.

Syntax
REURNING expr INTO variable
• expr is a valid PL/SQL or SQL expression, which can include columns or pseudocolumns
of the current table.
• Variable is the PL/SQL variable into which the result will be stored.
BULK COLLECT clause
• It used to collect more than 1 row at a time.
• It is used as part of the SELECT INTO,FETCH INTO , or RETURNING INTO clause
and will retrieve rows from the query into the indicated collections.
BULK COLLECT clause with SELECT

Illustrations
SQL> DECLARE
TYPE name IS TABLE OF
emp.ename%TYPE INDEX BY BINARY_INTEGER;
TYPE pays IS TABLE OF
emp.sal%TYPE INDEX BY BINARY_INTEGER;
n name;
p pays;
BEGIN
SELECT ename,sal BULK COLLECT INTO n,p
FROM emp;
FOR i IN 1..n.COUNT
LOOP
Display(RPAD(n(i),9,' ')||' '||p(i));
END LOOP;
END;
BULK COLLECT clause DELETE

Table delete_log
ename varchar2(20),
basic number(7,2),
dod timestamp
SQL> DECLARE
TYPE name IS TABLE OF
emp.ename%TYPE INDEX BY BINARY_INTEGER;
TYPE pays IS TABLE OF
emp.sal%TYPE INDEX BY BINARY_INTEGER;
n name;
p pays;
BEGIN
DELETE FROM emp
WHERE deptno=30

315 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

RETURNING ename,sal BULK COLLECT INTO n,p;


FOR i IN 1..n.COUNT
LOOP
Display(RPAD(n(i),9,' ')||' '||p(i));
IF p(i)>2500 THEN
INSERT INTO delete_log VALUES(n(i),p(i),sysdate);
END IF;
END LOOP;
END;
BULK COLLECT clause UPDATE

SQL> DECLARE
TYPE name IS TABLE OF
emp.ename%TYPE INDEX BY BINARY_INTEGER;
TYPE pays IS TABLE OF
emp.sal%TYPE INDEX BY BINARY_INTEGER;
n name;
p pays;
BEGIN
UPDATE emp SET sal=sal+sal*0.35
WHERE deptno=20
RETURNING ename,sal BULK COLLECT INTO n,p;
FOR i IN 1..n.COUNT
LOOP
Display(RPAD(n(i),9,' ')||' '||p(i));
IF p(i)>2500 THEN
INSERT INTO trace VALUES(n(i),p(i),sysdate);
END IF;
END LOOP;
END;

BULK COLLECT clause CURSOR


SQL> DECLARE
TYPE name IS TABLE OF
emp.ename%TYPE INDEX BY BINARY_INTEGER;
TYPE pays IS TABLE OF
emp.sal%TYPE INDEX BY BINARY_INTEGER;
CURSOR c_bulkcollect IS
SELECT ename,sal FROM emp;
n name;
p pays;
BEGIN
OPEN c_bulkcollect;
FETCH c_bulkcollect BULK COLLECT INTO n,p;
FOR i IN 1..n.COUNT
LOOP

316 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Display(RPAD(n(i),9,' ')||' '||p(i));


END LOOP;
END;

Differences between Anonymous and Named PL/SQL block.


Anonymous PL/SQL Block Named PL/SQL Block
1.This is an unnamed PL/SQL block 1.This is a named PL/SQL block
2.These are stored in operating system 2.These are stored in oracle database.
3.There is no security 3.Oracle is providing security
4.There is no information hiding facility 4.There is a hiding facility.
5. It requires every time compilation process. 5.It is compiled once and ready to execute
6.Granting privileges on this is not possible. 6.Granting privileges is possible.
7.These are not accessible to other program. 7. These are accessible by other oracle
tools like SQL*PLUS ,Oracle Forms
,Reports

Subprograms in PL/SQL


Subprograms are used to provide modularity and encapsulate a
sequence of statements.
• once subprograms are built and validated, they can be used in a
number of applications.
• Subprogram also provide abstraction.
• Subprograms are named PL/SQL blocks that can accepts parameters.
• A Subprogram can also have a declarative part, an executable part
and an exception handling part.
Important features of subprogram

Modularity
• Subprograms allow us to break a program into manageable, well-
defined logical modules.
Reusability
• Subprograms once executed can be used in any number of
application.
Maintainability
• Subprograms can simplify maintenance, because if a subprogram is
affected, only its definition changes.

317 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Procedures
o A procedure is a subprogram that performs a specific action.
o A procedure may or may not return value.
Syntax
CREATE OR REPLACE PROCEDURE procedureName(parname1[MODE] parType,..)
IS
[Local variable declaration;]
BEGIN
Executable Stage
EXCEPTION
Exception Handlers;
END [ProcedureName];
• Procedure can have o or many parameters.
• Every PROCEDURE consists of TWO parts
▪ The header of the procedure.
▪ The body of the procedure.
The Header
• It comes before the AS/IS keyword.
• It contains the PROCEDURE NAME and the PARAMETER LIST.

The Body
• It is any thing or every thing that is existing after the AS keyword.
• The word REPLACE is optional.
Execute a Procedure
At SQL Prompt
>EXECUTE/EXEC PROCEDURE_NAME
Call the Procedure in another PL/SQL Block
SQL>BEGIN
PROCEDURE_NAME;
END;
• The procedure details are stored in
o USER_SOURCE
o USER_OBJECTS

CREATE OR REPLACE PROCEDURE cal_intr


(P number,N number,R number)
IS
si number(14,2);
ci number(16,2);
BEGIN
si:=(P*N*R)/100;
ci:=power((1+r/100),n);--not case sensitive
ci:=p*ci;
dbms_output.put_line('simple interest is:'||si);
dbms_output.put_line('compound interest is:'||ci);
END cal_intr;

318 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

To view the Procedure availability


SQL>SELECT object_name ,object_type,status
FROM USER_OBJECTS
WHERE object_name=’PROC_NAME’;
Illustration
SQL> SELECT object_name ,object_type,status
FROM USER_OBJECTS
WHERE object_name='CAL_INTR';

SQL> SELECT line||'>',text FROM user_source


WHERE name='PROC_NAME';
Illustration
SQL> SELECT line||'>',text FROM user_source
WHERE name='CAL_INTR';

Recompile an Existing Procedure


Syntax
SQL>ALTER PROCEDURE procedurename compile;
Illustration
SQL>ALTER PROCEDURE cal_intr COMPILE

SQL>CREATE OR REPALCE procedure proc_bonus


as
cursor cb is
select empno,ename,job,sal+nvl(comm,0) netsal
from emp;
i cb%rowtype;
bonus number;
begin
open cb;
loop
fetch cb into i;
exit when cb%notfound;
if i.job='CLERK' then
bonus:=i.netsal*0.15;
elsif i.job='SALESMAN' then
bonus:=i.netsal*0.25;
else
bonus:=i.netsal*0.35;
end if;
update emp set sal=sal+bonus
where empno=i.empno;
display(rpad(i.ename,8)||' '||rpad(i.job,8)||' '||bonus);
end loop;
close cb;
END proc_bonus;

319 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Subprogram Parameters
• PARAMETERS are the mean to pass values TO and FROM the calling
environments to the oracle server.
• PARAMETERS are the values that will be processed or returned via the
EXECUTION of the PROCEDURE or FUNCTION.
• These PARAMETERS can have different modes.
Parameter Modes
• There are three types of modes
o IN Mode
o OUT Mode
o INOUT Mode
IN MODE
• It is the Default mode of subprogram.
• Passes a value into the program , from the calling environment.
• It is READ ONLY value.
OUT MODE
• Used to return a value from subprogram.
• It is WRITE ONLY value.
• Passes a valued back from the program to the calling environment.
• Cannot be assigned default values.
• Value assigned only if the program is successful.
INOUT MODE
• Carriers a value into a subprogram.
• Returns value from sub program.
• Values will be READ from the calling environment and then WRITTEN to
the calling environment.
SQL> CREATE OR REPLACE PROCEDURE
proc_sc(n in NUMBER,s OUT NUMBER,c OUT NUMBER)
IS
BEGIN
s:=n*n;
c:=s*n;
END proc_sc; .
> var sr NUMBER
> VAR cr NUMBER
> EXEC proc_sc(10,:sr,:cr)

Calling in PL/SQL block

SQL>DECLARE
n NUMBER:=&no;
vs NUMBER;
vc NUMBER;
BEGIN
proc_sc(n,vs,vc);
display('The '||n||' seq and cube values are '||vs||' '||vc);

320 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

END;

SQL>DECLARE
n NUMBER:=&no;
BEGIN
proc_sc(n,:sr,:cr);
display('The '||n||' seq and cube values are '||:sr||' '||:cr);
END;

SQL>CREATE OR REPLACE PROCEDURE


proc_dtsal(pdts IN OUT NUMBER
.
)
IS
BEGIN
SELECT SUM(sal) INTO pdts
FROM emp
WHERE deptno=pdts;
END proc_dtsal;
SQL> CREATE OR REPLACE PROCEDURE
proc_dtsal(pdts IN OUT NUMBER)
IS
BEGIN
SELECT SUM(sal) INTO pdts
FROM emp
WHERE deptno=pdts;
END proc_dtsal;

.
> var bdts NUMBER
>EXEC :bdts:=10
SQL> CREATE OR REPLACE PROCEDURE
add_dept(pdname IN dept.dname%TYPE DEFAULT 'UNKNOW',
ploc IN dept.loc%TYPE DEFAULT 'UNKNOW')
IS
BEGIN
INSERT INTO dept VALUES(ds.nextval,pdname,ploc);
END add_dept;
Note:
If want insert value only for ‘loc’
Types of sending arguments to the subprogram
Position Notation
• It is simple an association of the values by POSITION of the arguments at
call time with that of declaration in the header of the procedure creation.
• The order of the parameters used when executing the procedure should
match the order in the PROCEDURES HEADER exactly.

321 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Named Notions(=>)
• It is an explicit association using the symbol =>
Syntax
Formalparametername=>ArgValue
• In named notation the order of parameters in does not matter.
• If the notation is mixed then position notation should be used first then
the named notation should be used.

SQL>GRANT EXECUTE ON cal_intr to miller;


MILLER
SQL>EXEC scott.cal_intr(1000,12,2)
Synonym for Procedure
SQL>Create [public] Synonym <Synonym Name> for <Procedure Name>;
SQL> Create public Synonym sci FOR cal_intr;
SQL> GRANT EXECUTE ON sci TO PUBLIC;

MILLER
SQL>exec sci(1000,12,2)
Note: Synonym can’t be created for Procedure which is defined in
Package.

pragma autonomous_transaction

• Prior to Oracle 8i and higher .(Autonomous--in_depended).


• It Used in nested procedure to make each procedure in_depended for TCL.
• Allow to write TCL in Trigger.
• It must appear in the declarative section of the block ,and only one pragma is
allowed in the block.
• It can go anywhere in the declarative section ,but is it good style to put it at the
beginning.

SQL>CREATE OR REPLACE PROCEDURE add_emp


AS
BEGIN
INSERT INTO emp(empno,ename,job,sal,deptno)
VALUES(7001,'EFCODD','MANAGER',2000,50);
COMMIT;
END add_emp;
SQL>CREATE OR REPLACE PROCEDURE add_dept
AS
BEGIN
INSERT INTO dept
VALUES(50,'EXPORT','BLORE');
add_emp;

322 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

END add_dept;

How to store Images

SQL>CREATE OR REPLACE procedure load(fname varchar2)


as
f_lob bfile;
b_lob blob;
Begin
insert into Images
values(fname,substr(fname,instr(fname,'.')+1)
,empty_blob())
RETURN image into b_lob;
f_lob:=BFILENAME('KRISHNA',fname);
dbms_lob.fileopen(f_lob,dbms_lob.file_readonly); dbms_lob.loadfromfile(b_lob,f_lob,
dbms_lob.getlength(f_lob));
dbms_lob.fileclose(f_lob);
commit;
end load;

Dropping Procedure
• Similar to dropping a table procedure can also be dropped.
Syntax
SQL> DROP PROCEDUE procedure_name;
Illustration
SQL>DROP PROCEDURE cal_intr;

USER DEFINED FUNCTIONS


• A function is very similar to a procedure.
• Function is a named PL/SQL block and it may or my not take the
parameters but it must return a value.
• Function must have a RETURN clause in the EXECUTABLE section of a
FUNCTION.
• Functions are mainly used to perform the calculation.
• The data type of the return values must be declared in the header of
the function.
• Procedures and Functions are different forms of PL/SQL blocks, with a
declared, executable, and exception section.
• Procedures and Functions can be stored in the database or declared
within a block.
• A procedure call is a PL/SQL statement by itself, while a function call is
called as part of an expression.

323 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

• A function has output that needs to be assigned to a variable or it can


be used in a SELECT statement.
• Function can not call when it has RETURN data type as Boolean.
• A Function can contain more than one RETURN statement, each
Exception should have a RETURN statement.
Syntax
CREATE [OR REPLACE]
FUNCTION <Function name>(parameter List)
RETURN data type
IS
[Local variables]
BEGIN
<Body>
RETURN(value);
EXCEPTION
<Defined pragmas>
END [Function name];

>CREATE OR REPLACE FUNCTION cal_intr


(P NUMBER,N NUMBER,R NUMBER)
RETURN NUMBER
IS
v_ci NUMBER(16,2);
BEGIN
v_ci:=POWER((1+r/100),n);
v_ci:=p*v_ci;
RETURN(v_ci);
END;
Calling function at SQL:-
>var cint number;
>exec :cint:=cal_intr(1000,12,2);
>print :cint;
Calling function with SELECT statement
>SELECT cal_intr(1000,12,2) FROM dual;
> SELECT ename,hiredate,sal,ROUND(cal_intr(sal,12,2)) "cintr"
FROM emp

Calling Function In PL/SQL block


DECLARE
v_cintr NUMBER;
BEGIN
V_cintr:= cal_intr(1000,12,2);
DISPLAY(‘The Compound Intr is: ’||v_cintr);
END;

324 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

/
CREATE OR REPLACE FUNCTION leapyear
(y NUMBER)
RETURN VARCHAR2
IS
BEGIN
IF (MOD(y,400)=0)OR (MOD(y,100)!=0 and MOD(y,4)=0) THEN
RETURN('Leap Year');
ELSE
RETURN('Not Leap Year');
END IF;
END;
/
Q)Write a function to accept the empno and return exp with minimum 3
decimal?
CREATE OR REPLACE FUNCTION empexp(p_empno
emp.empno%TYPE)
RETURN NUMBER
IS
v_hiredate emp.hiredate%TYPE;
v_exp NUMBER(6,3);
BEGIN
SELECT hiredate INTO v_hiredate
FROM emp
WHERE empno=p_empno;
v_exp:=MONTHS_BETWEEN(SYSDATE,v_hiredate)/12;
RETURN v_exp;
END;
Q) Write a function to accept the deptno and return the No of emps in that
deptno.
CREATE OR REPLACE FUNCTION noe(p_deptno emp.deptno%TYPE)
RETURN NUMBER
IS
v_noe NUMBER(6,3);
BEGIN
SELECT count(empno) INTO v_noe
FROM emp
WHERE deptno=p_deptno;
RETURN v_noe;
END;
> select unique deptno,noe(deptno)
from emp
where noe(deptno)>3;

325 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Database TRIGGERS
Database TRIGGERS
• A Trigger set of PL/SQL statements automatically executed whenever an DML
statement is performed on table.
• It is a PL / SQL Block like a Procedure. i.e., to perform some specific task. But a
procedure always requires an explicit call for execution but triggers are executed
automatically when any triggering event occurs.
• It is Associated with a Table or View.
• INSERT,UPDATE,DELETE are considered as the triggering events of the
database trigger. These events initiate the firing of trigger.
• The firing of trigger is nothing but the execution of the PL/SQL code associated
to that trigger.
• It is also a Database Object.
Advantages:
• A database trigger is a security object to provide security to the table like
tracking the transaction.
• A database trigger is also used to define the complex business constraints
that cannot be defined by using integrity constraints.
• Automatically generating values for derived columns or PRIMARY KEY
columns.
• Used to implement user defined restrictions on table.
• provides high security.
• Activated when table are manipulated from other application software also.
Syntax:
SQL>CRAETE [OR REPLACE ] TRIGGER triggername
AFTER/BEFORE INSERT or UPDATE or DELETE
[OF columnname] ON tablename
[FOR EACH ROW]
[WHEN condition]
DECLARE
Declaration statements;
BEGIN
Executable statements;
[EXCEPTION
Exception handling;]
END [trg_name];
• Trigger can not be duplicate trigger name .
• Trigger can be attached one table
• When condition is true, trigger will be executed otherwise not executed.

326 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

The specification
New&Old
• Refers to the values available in DML statements.
• Valid in row trigger only.

New&Old:-
→Refers to the values available in DML stmts.
→Valid in row trigger only

New Old
Insert
Update
Delete

Kinds of Triggers

Application Database
Trigger Trigger

327 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Application Trigger

• It is fired when DML Event occurs Within the Application.


Example : Oracle Forms

Database Trigger
• It is fired when DML Event occurs on a Table / View, no matter which User
is connected.

Component of Trigger

PL / SQL
.Insert Code
.Update Triggering Trigger
.Delete Event Action

Trigger
Restriction
WHEN
Trigger Parts
• Indicates when to activate the trigger. i.e., defines whether the trigger fires before
or after the statement is executed.
Before Triggers
• These TRIGGERS fire BEFORE any transactions are implemented.
• These TRIGGERS can be classified as
o BEFORE INSERT
o BEFORE UPDATE
o BEFORE DELETE
Usage
• When a trigger provides values for derived columns BEFORE the INSERT OR
UPDATE statement is completed.
• When a trigger determines whether an INSERT,UPDATE or DELETE statement
should be allowed to completed.

328 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

After Triggers
• These TRIGGERS fire AFTER any transaction is implemented.
• These TRIGGERS can be classified as
o AFTER INSERT
o AFTER UPDATE
o AFTER DELETE
Usage
• When a TRIGGER should fire after a DML statement is executed for
acknowledgement purpose or auditing.
• When a TRIGGER should perform action not specified in a BEFORE trigger.

Restrictions
• A trigger may not issue a transactional control statement like
COMMIT,SAVEPOINT and ROLLBACK.
• Any FUNCTION or PROCEDURE called by a trigger cannot issues a transaction
control statement.
Level of Triggers
• Trigger can be define at two different levels.
• They are
1)Row level
2)Statement or table level
Row level Trigger
• A row trigger is fired as many times as there are rows affected by triggering
event.
• When the statement FOR EACH ROW is present in the CREATE TRIGGER
clause, the trigger is a ROW trigger.
Statement Level
• Trigger will be fired only once for DML statement.
Trigger Body
• A set of PL/SQL statements.

The WHEN clause


• The WHEN clause is valid for row-level triggers only.
• The trigger body will be executed only for those rows that meet the condition.
Syntax:
WHEN trigger_condition

• The :new and :old records can be referenced inside trigger_condition as well.
• The colon is only valid in the trigger body.

329 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

• Activated when table are manipulated from other application software also.

Database

Applications
Table
Update Update Trg
….
….
Insert
…. Insert Trg
….
Delete
…. Delete Trg

How many Trigger are there


Mxm-12 Trigger.
Row level

After Insert Before Insert


After Update Before Update
After Delete Before Delete

Table Level

After Insert Before Insert


After Update Before Update
After Delete Before Delete

SQL>create or replace trigger trg_upp_con


before insert or update
of name on kcb_acc_tab
FOR EACH ROW
BEGIN
:NEW.name:=UPPER(:NEW.name);

330 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

END trg_upp_con;

SQL> CREATE OR REPLACE TRIGGER trg_nnd


BEFORE INSERT OR UPDATE
OF dname ON dept
FOR EACH ROW
DECLARE
cnt NUMBER;
pragma autonomous_transaction;
BEGIN
SELECT count(*) INTO cnt
FROM DEPT
WHERE dname=:NEW.DNAME;
IF cnt>0 THEN
RAISE_APPLICATION_ERROR
(-20345,'The dname con not be dup');
ELSIF :NEW.dname IS NULL THEN
RAISE_APPLICATION_ERROR
(-20346,'The dname con not be null');
END IF;
END trg_nnd;

Table delete_log
ecode NUMBER(4),
ename VARCHAR2(20),
basic NUMBER(7,2),
dod timestamp

SQL>CREATE OR REPLACE TRIGGER trg_del


AFTER delete
ON emp
FOR EACH ROW
BEGIN
INSERT INTO delete_log VALUES(:OLD.empno,:OLD.ename,:OLD.sal,sysdate);
END trg_del;

Table Trace
-----------------
Userid varchar2(20),
dod timestamp

SQL>CREATE OR REPLACE TRIGGER trg_del


AFTER delete
ON emp
FOR EACH ROW
BEGIN

331 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

INSERT INTO trace VALUES(user,sysdate);


END trg_del;
SQL>CREATE OR REPLACE TRIGGER trg_bonus
AFTER INSERT
ON emp
FOR EACH ROW
DECLARE
pragma autonomous_transaction;
BEGIN
INSERT INTO bonus VALUES(:NEW.ename,:NEW.job,:NEW.sal,:NEW.comm);
COMMIT;
END trg_bonus;
It gives Run time error .
ORA-04092: cannot COMMIT in a trigger
SQL> rollback;
Emp table transactions only will rollback;

SQL>CREATE OR REPLACE TRIGGER trg_sal


AFTER delete
ON EMP
FOR EACH ROW
WHEN (old.sal>1500) --
BEGIN
INSERT INTO delete_log
VALUES(:OLD.empno,:OLD.ename,:OLD.sal,sysdate);
END trg_sal;

3 events on single Trigger:-


(insert,update,delete)

CREATE [OR REPLACE ] TRIGGER <trg_name>


BEFORE/AFTER insert OR update OR delete
ON <tablename>
[FOR EACH ROW]
[When condition]

[DECLARE]

BEGIN
IF Inserting THEN
SQL Statements
END IF;
IF updating THEN
SQL Statements
END IF;
IF deleting THEN

332 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

SQL Statements
END IF;

END [trg_name];

> desc INT_TAB


Name Type
----------------------------------- -------- ------------------------
ECODE NUMBER(4)
NAME VARCHAR2(10)
DEPTNO NUMBER(2)

SQL> desc UPD_TAB


Name Null? Type
----------------------------------------------------------------- -------- --------------
ECODE NUMBER(4)
NAME VARCHAR2(10)
USAL NUMBER(7,2)

SQL> desc del_tab


Name Null? Type
----------------------------------------------------------------- -------- ------------------
ECODE NUMBER(4)
NAME VARCHAR2(10)
JOB VARCHAR2(9)

SQL> CREATE OR REPLACE TRIGGER trg_iud


AFTER insert OR update OR delete
ON emp
FOR EACH ROW
BEGIN
IF Inserting THEN
INSERT INTO int_tab
VALUES(:NEW.empno,:NEW.ename,:NEW.deptno);
END IF;
IF updating THEN
INSERT INTO upd_tab
VALUES(:NEW.empno,:NEW.ename,:NEW.sal);
END IF;
IF deleting THEN
INSERT INTO del_tab
VALUES(:OLD.empno,:OLD.ename,:OLD.job);
END IF;
END trg_uid;

Table job_list

333 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Job low_pay high_pay


Clerk 3000 8000
Salesman 4000 12000
Annalist 8000 25000
Manager 6000 20000

SQL>CREATE OR REPLACE TRIGGER trg_job


BEFORE insert OR update
ON EMP
for each row
WHEN (NEW.job<>'PRESIDENT')
DECLARE
i job_list%ROWTYPE;
BEGIN
SELECT low_pay,high_pay INTO i.low_pay,i.high_pay
FROM job_list
WHERE job=INITCAP(:NEW.job);
IF :NEW.sal NOT BETWEEN i.low_pay AND i.high_pay THEN
RAISE_APPLICATION_ERROR
(-20345,:NEW.job ||' sal in between '||i.low_pay||' and '||i.high_pay);
END IF;
exception
WHEN no_data_found THEN
RAISE_APPLICATION_ERROR
(-20346,:NEW.job||' is not exists in job_list table');
END trg_job;

SQL>CREATE OR REPLACE TRIGGER trg_wht


BEFORE INSERT OR UPDATE OR DELETE
ON emp
DECLARE
cnt NUMBER;
BEGIN
SELECT COUNT(*) INTO cnt
FROM htab
WHERE TO_CHAR(HDAY,'DD-MON-YY')=TO_CHAR(SYSDATE,'DD-MON-YY');
IF TO_CHAR(SYSDATE,'DY') IN('SAT','SUN') THEN
RAISE_APPLICATION_ERROR(-20345,'No transaction in week end');
ELSIF cnt>0 THEN
RAISE_APPLICATION_ERROR(-20347,'No transaction in Hday');
ELSIF TO_CHAR(sysdate,'HH24') NOT BETWEEN 9 AND 19 THEN
RAISE_APPLICATION_ERROR(-20348,'No transaction in this time');
END IF;
END trg_wht;

334 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Remove trigger
Syntax
SQL>DROP TRIGGER <trg_name>;
SQL>DROP TRIGGER trg_wht;

To disable all triggers on Table


SQL> ALTER TABLE <tabname> DISABLE ALL TRIGGERS;
SQL>ALTER TABLE emp DISABLE ALL TRIGGERS;
To Enable all triggers on Table
SQL> ALTER TABLE <tabname> ENABLE ALL TRIGGERS;
SQL > ALTER TABLE emp ENABLE ALL TRIGGERS;
To disable single trigger on Table
Syntax
SQL>ALTER TRIGGER trg_name DISABLE;
SQL>ALTER TRIGGER trg_wht DISABLE;
To enable single trigger on Table
Syntax
SQL>ALTER TRIGGER trg_name ENABLE;
SQL>ALTER TRIGGER trg_wht ENABLE;
SQL> SELECT TRIGGER_TYPE,TRIGGERING_EVENT,STATUS
from user_triggers
WHERE TRIGGER_NAME='TRG_WHT';
To view the source code of Trigger
SQL>SELECT text FROM user_source
WHERE name='TRG_WHT';
Instead of Triggers(8i)
→Trigger on view
→used to manipulate join views
Instead of →insert
→update
→delete
SQL> CREATE VIEW ev
AS
SELECT *FROM emp;
SQL> CREATE OR REPLACE TRIGGER trg_ev
Instead of DELETE
ON ev
BEGIN
display('Record is removed');
END trg_ev;
SQL> CREATE OR REPLACE VIEW ed_view
AS
SELECT empno,ename,job,sal,e.deptno,dname,loc
FROM emp e,dept d
WHERE e.deptno=d.deptno;

335 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

SQL> CREATE OR REPLACE TRIGGER trg_ed


instead of DELETE
ON ed_view
BEGIN
DELETE FROM emp
WHERE deptno=:OLD.deptno;
DELETE FROM dept
WHERE deptno=:OLD.deptno;
END trg_ed;
DDL TRIGGERS
• The only difference between DML and DDL triggers is the firing event.
• You use DDL triggers to enforce rules or audit the creation of database objects.
• We create a table name AUDIT_CREATION.
SQL>Create table audit_creation
(audit_creation_id number constraint acid primary key,
audit_owner_name varchar2(30) constraint audit_creation_nn1 not null,
audit_obj_name varchar2(30) constraint audit_creation_nn2 not null,
audit_date date constraint audit_creation_nn3 not null);

Even attribute Function


ORG_DICT_OBJ_OWNER
• This function takes no formal parameter.
• It Returns no owner of the object acted upon by the event as a VARCHAR2 datatype.
ORA_DICT_OBJ_NAME
• It return an object name as a VARCHAR2 datatype.
• The object name represents the target of the DDL statement.

This trigger tracks the creation all objects, including which user issued the
CREATE statement.

>CREATE OR REPLACE TRIGGER audit_creation


Before create on SCHEMA
BEGIN
INSERT INTO audit_creation
VALUES(audit_creation_s1.nextval,
ORA_DICT_OBJ_OWNER,
ORA_DICT_OBJ_NAME,
SYSDATE);
END;

336 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Database packages

Packages
• It is logical group of objects such as
o Functions
o Procedures
o Global variables
o Cursors
Advantages
• Packages allow us to organize our application development more efficiently.
• Packages allow us to grant the privileges more efficiently.
• It allows the Oracle Server to Read Multiple Objects into Memory at Once.
• Packages can contain global variables and cursors that are available to all procedures and
functions in the packages.
• Packages allow us to overload procedure and functions.
• All related program objects are stored in one particular location in the memory
(which reduce the search process) stored in USER_SOURCE.

• Package has two parts, with are individually coded.


o Package specification
o Package body

Components of a Package
--Specification
--Body

Application Database
Package

Specification

Body

337 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Package Specification
• The PACKAGE SPECIFICATION contains information about the contents of the
package.
• PACKAGE SPECIFICATION contains declarations of GLOBAL/PUBLIC variables.
• All object placed in the PACKAGE SPECIFICATION are called PUBLIC OBJECTS.
such objects are called public objects

Syntax for Specification:


CREATE [OR REPLACE ] PACKAGE <Pkg Name>
IS/AS
type_definition
PROCEDURE <proc name>( parameter )
FUNCTION <fun name>( parameter ) RETURN datatype;
Variable_declaration;
Exception_declaration;
Cursor_declaration;
END [Pkg Name];
Package Body
• The PACKAGE BODY is a separate data dictionary object from the package header.
• The PACKAGE BODY contains the actual executable code for the OBJECTS described in
the PACKAGE SPECIFICATION.
• The PACKAGE BODY contain code for all procedures and function described in the
specification.
• When creating stored package the package specification and body can be complied
separately.
Syntax for Body:
CREATE [OR REPLACE ] PACKAGE BODY <Pkg Name>
IS/AS
[Private variable declaration];
PROCEDURE <procedure name>(arg list)
IS
………………..
…………………
END [procedure name];
FUNCTION <function name>(arg list)
RETURN datatype
IS
BEGIN
……………………..
…………………….
END [function name];

END <Pkg Name>;

338 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Invoking Package Constructs


>Execute <Package Name>.<Prog Name>;

Bodiless Package
• We can declare Package Specification that does not need Package body.

SQL>CREATE OR REPLACE PACKAGE pack_am


AS
PROCEDURE add_num(m IN NUMBER,n IN NUMBER);
FUNCTION mul_num(x IN NUMBER,y IN NUMBER)
RETURN number;
result NUMBER;
END pack_am;
SQL> CREATE OR REPLACE PACKAGE BODY pack_am
AS
PROCEDURE add_num(m IN NUMBER,n IN NUMBER)
IS
BEGIN
result:=m+n;
display('The sum of m,n is '||result);
END add_num;
FUNCTION mul_num(x IN NUMBER,y IN NUMBER)
RETURN number
IS
BEGIN
result:=x*y;
RETURN(result);
END mul_num;
END pack_am;

SQL>CREATE OR REPLACE PACKAGE pack_eg


AS
FUNCTION exp(pdoj IN DATE) RETURN NUMBER;
FUNCTION gross(pbasic IN NUMBER) RETURN NUMBER;
END pack_eg;
SQL>CREATE OR REPLACE PACKAGE BODY pack_eg
AS
FUNCTION exp(pdoj IN DATE)
RETURN NUMBER
IS
BEGIN
RETURN(round(MONTHS_between(SYSDATE,pdoj)/12));
END exp;
FUNCTION gross(pbasic IN NUMBER)
RETURN NUMBER
IS

339 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

BEGIN
RETURN(pbasic+pbasic*0.45+pbasic*0.35-pbasic*0.15);
END gross;
END pack_eg;

SQL>select pack_eg.exp('14-jun-95'),pack_eg.gross(1000) from dual;


SQL> select ename,hiredate,pack_eg.exp(hiredate),
sal,pack_eg.gross(sal)
from emp
WHERE pack_eg.exp(hiredate)>30;

Function over loading


SQL>CREATE OR REPLACE PACKAGE pack_fo
AS
FUNCTION fun_add(m IN NUMBER,n IN NUMBER)
RETURN NUMBER;
FUNCTION fun_add(x IN VARCHAR2,y IN VARCHAR2)
RETURN VARCHAR2;
END pack_fo;
SQL>CREATE OR REPLACE PACKAGE BODY pack_fo
AS
FUNCTION fun_add(m IN NUMBER,n IN NUMBER)
RETURN NUMBER
IS
BEGIN
RETURN(m+n);
END fun_add;
FUNCTION fun_add(x IN VARCHAR2,y IN VARCHAR2)
RETURN VARCHAR2
IS
BEGIN
RETURN(x||' '||y);
END fun_add;
END pack_fo;
SQL> SELECT pack_fo.fun_add(100,200)
"Res1",pack_fo.fun_add('KRISHNA','ORACLE') "Res2"
from dual;

→Package will be stored in USER_SOURCE


SQL> SELECT TEXT FROM USER_SOURCE
WHERE NAME='PACK_EG';
Remove the package:-

SQL>DROP PACKAGE <packname>;

SQL>CREATE OR REPLACE PACKAGE pack_bal

340 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

AS
PROCEDURE upd_bal(paccno IN kcb_acc_tab.accno%TYPE,
pttype IN kcb_tran_tab.ttype%TYPE,
pamt IN kcb_tran_tab.amt%TYPE);
FUNCTION chk_bal(paccno IN kcb_acc_tab.accno%TYPE,
pamt IN kcb_tran_tab.amt%TYPE)
RETURN BOOLEAN;
FUNCTION fnow(paccno IN kcb_acc_tab.accno%TYPE)
RETURN NUMBER;
FUNCTION ftwa(paccno IN kcb_acc_tab.accno%TYPE)
RETURN NUMBER;
cbal kcb_acc_tab.bal%TYPE;
END pack_bal;

SQL> PACKAGE BODY pack_bal


AS
PROCEDURE upd_bal(paccno IN kcb_acc_tab.accno%TYPE,
pttype IN kcb_tran_tab.ttype%TYPE,
pamt IN kcb_tran_tab.amt%TYPE)
IS
BEGIN
SELECT bal INTO cbal
FROM kcb_acc_tab
WHERE accno=paccno;
IF upper(pttype)='D' THEN
cbal:=cbal+pamt;
elsif upper(pttype)='W' THEN
cbal:=cbal-pamt;
END IF;
UPDATE kcb_acc_tab SET bal=cbal
WHERE accno=paccno;
END upd_bal;
FUNCTION chk_bal(paccno IN kcb_acc_tab.accno%TYPE,
pamt IN kcb_tran_tab.amt%TYPE)
RETURN BOOLEAN
IS
vacctype kcb_acc_tab.acctype%type;
BEGIN
SELECT acctype,bal INTO vacctype,cbal
FROM kcb_acc_tab
WHERE accno=paccno;
cbal:=cbal-pamt;
IF cbal<5000 AND vacctype='S' THEN
RETURN(false);
ELSIF cbal<10000 AND vacctype='C' THEN
RETURN(false);

341 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

ELSE
RETURN(true);
END IF;
END chk_bal;
FUNCTION fnow(paccno IN kcb_acc_tab.accno%TYPE)
RETURN NUMBER
IS
vnow NUMBER;
BEGIN
SELECT count(*) INTO vnow
FROM kcb_tran_tab
WHERE accno=paccno AND
ttype='W' AND TO_CHAR(dot,'DD-MON-YY')=
TO_CHAR(sysdate,'DD-MON-YY') AND
EXISTS (SELECT 'krishna'
FROM kcb_acc_tab
WHERE accno=paccno AND
acctype='S');
RETURN(vnow);
END fnow;
FUNCTION ftwa(paccno IN kcb_acc_tab.accno%TYPE)
RETURN NUMBER
IS
vtwa NUMBER;
BEGIN
SELECT sum(amt) INTO vtwa
FROM kcb_tran_tab
WHERE accno=paccno AND
ttype='W' AND
TO_CHAR(dot,'DD-MON-YY')=
TO_CHAR(sysdate,'DD-MON-YY') AND
EXISTS (SELECT 'krishna'
FROM kcb_acc_tab
WHERE accno=paccno AND
acctype='S');
IF vtwa IS NULL THEN
vtwa:=0;
END IF;
RETURN(vtwa);
END ftwa;
END pack_bal;

Dynamic Cursor in package


SQL>CREATE OR REPLACE PACKAGE sc_fm
IS
type r_comp is record

342 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

(deptno emp.deptno%type,
ename emp.ename%type,
hiredate emp.hiredate%type,
sal emp.sal%type,
total_sal emp.sal%type);
TYPE comp_rc IS REF CURSOR
RETURN r_comp;
FUNCTION fun_emp(p_deptno NUMBER)
RETURN comp_rc;
END sc_fm ;

SQL> CREATE OR REPLACE PACKAGE BODY sc_fm


IS
FUNCTION fun_emp(p_deptno NUMBER)
RETURN comp_rc
IS
c_emp sc_fm.comp_rc;
v_raise NUMBER;
BEGIN
IF p_deptno>=40 THEN
v_raise :=1.4;
ELSIF p_deptno=30 THEN
v_raise :=1.3;
ELSIF p_deptno=20 THEN
v_raise :=1.2;
ELSE
v_raise:=1.1;
END IF;
OPEN
c_emp FOR
SELECT deptno,ename,hiredate,sal,
v_raise*(sal+nvl(comm,0)) total_sal
FROM emp
WHERE deptno=p_deptno;
RETURN c_emp;
END fun_emp;
END sc_fm;

Dynamic SQL
• Within PL/SQL, you can execute any kind of SQL statement(even data definition and
data control statements)
• In PL/SQL, such statements cannot be executed statically.
• when we want to execute a SQL data definition statement (such as CREATE)
• A data control statement (such as GRANT).
EXECUTE IMMEDIATE :-

343 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

• The EXECUTE IMMEDIATE statement prepares and immediately executes a dynamic


SQL statement or an anonymous PL/SQL block.
syntax
EXECUTE IMMEDIATE dynamic_string
SQL>CREATE OR REPLACE PROCEDURE
drop_table (table_name IN VARCHAR2)
AS
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE '|| table_name||' PURGE';
END drop_table;
SQL>CREATE OR REPLACE PROCEDURE proc_tg
AS
BEGIN
FOR i IN (SELECT 'GRANT SELECT ON '||table_name||' to krishna ' cmd
FROM user_tables)
LOOP
execute immediate i.cmd;
END LOOP;
EXCEPTION
when others then
dbms_output.put_line('error'||substr(sqlerrm,1,250));
END PROC_TG;

SQL> CREATE OR REPLACE PROCEDURE proc_tab_revoke


AS
BEGIN
FOR i IN (SELECT 'REVOKE SELECT ON '||table_name||' FROM krishna ' cmd
FROM user_tables)
LOOP
execute immediate i.cmd;
END LOOP;
EXCEPTION
when others then
dbms_output.put_line('error'||substr(sqlerrm,1,250));
END proc_tab_revoke;

UTL_FILE package(Out bound Interface)


UTL_FILE :
• This package will be used for inserting the data from flat file to table and table to flat
file.
• It has functions
UTL_FILE.FOPEN() : Using this function we will create a new file in the
UTL_FILE access directories.
UTL_FILE.PUTLINE() : using this function we inserting the data in file.
UTL_FILE.FCLOSE() : Using this function we will close the file after inserting
the data.

344 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

SQL>CREATE OR REPLACE PROCEDURE outbound


AS
CURSOR c1 IS
select empno,ename,job,hiredate,sal,deptno
FROM EMP;
Id UTL_FILE.FILE_TYPE;
BEGIN
Id:=UTL_FILE.FOPEN('KRISHNA’,'empf.txt','w');
FOR i IN c1
LOOP
UTL_FILE.PUT_LINE(id,i.EMPNO||','||i.ENAME||','||i.job||','||i.hiredate||','||i.sal||','||i.deptno);
END LOOP;
UTL_FILE.FCLOSE(id);
END outbound;

>create sequence order_seq


increment by 1
start with 1;
> create or replace package orderpkey_gen
is
master_key varchar2(10);
end orderpkey_gen;

> create or replace trigger order_no_gen


before insert
on sales_order
for each row
declare
primary_key_value varchar2(10);
begin
select lpad(to_char(order_seq.nextval),5,0) into primary_key_value
from dual;
orderpkey_gen.master_key:='O'||primary_key_value;
:new.s_order_no:=orderpkey_gen.master_key;
end order_no_gen;

> create or replace trigger fk_order_no_gen


before insert
on sales_order_details
for each row
begin
if :new.s_order_no is null then
:new.s_order_no:=orderpkey_gen.master_key;
end if;
end;

345 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Oracle Architecture:

via SQL * Net


User Listener Dnnn Multithreaded Server
Processes

Snpn
PMON

System Global Area


Shared Pool
Program Global Area

Private
Redo Log buffer
Buffer Cache

To distributed database nodes


RECO
LCKN LGWR CKPT DBWR

Oracle Process SMON


(Background process)
Archive
Destination

Redo
ARCH Logs
Data1.dbf
Data2.dbf
Data3.dbf
init.ora
Control File

Archiving redo logs


Fig 1.1
User Process
• When a user runs an application program such as a Pro* C program or an oracle
tool, such as server manager, oracle creates a user process to run the user’s
application.

→ User process will create in client side.


→SQL * Netlistener willrun on server for particular port.
→Listerer will listen for incoming requestand service the service the
request (It will create a server process on server).

346 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

Dispatcher Processes(Dnnn)
• The Dispather processes allow user processes to share a limited number of server
• Without a dispatcher, each user process requires one dedicaded server process.
Multithreaded Server(Shared server)
• In dedicated server architecture each user process will create a server process on the
server where as in shared server architecture each server process will be shared by
multiple user process.
• Or acle SGA (System Global Area):
▪ Oracle allocates a memory area called the System Global Area
(System Global Area) and starts one or more Oracle processes.
▪ A System Global Area is group of shared memory structure that
contain data and control information for one Oracle database instance.
Note:-the combination of SGA and the Oracle processes is called an oracle database
instance .
▪ The SGA ,consists of several elements.

o Buffer Cache:
▪ the buffer cache stores Oracle data in memory for users to view to
view or change in this way ,user never make changes directly to disk
files.

o Redu log Buffer:


▪ the log buffer stores special information called redo ,which helps
oracle reconstruct data changes in the event of system failure .

o Shared Pool:
▪ components of the shared pool including the cache ,for storing parsed
SQL statement for reuse by other users.

o Library Cache :
▪ the library cache includes shared SQL areas. Private SQL areas
,PL/SQL procedures and packages and control structure such as locks
and library cache handles.

o Dictionary Cache:
▪ the data dictionary is a collection of database tables and views and its
users.
o Data dictionary stores
o Names of all tables and views in the database .
o Names and data types of columns in database tables .
o Privileges of all oracles users

347 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

o Server Processes :
Server process created on behalf of each user’s application may perform one or more of
the following :
▪ Parse and execute SQL statement issued via the application .
▪ Read necessary data block from disk (data files ) into the shared
database buffer of the SGA ,if the blocks are not already presents in
the SGA.

o Background Processes :

The background processes in an Oracle instance include the following

▪ Lock (LCKn):
• With the parallel server option ,up to ten lock processes
(LCKn,……….LCK9)provide inter-instance locking .however
a single LCK processes (LCK0)is sufficient for most parallel
Server System .
▪ Database Writer(DBWR) :
• Database Writer process writer buffer to data files .
• The primary job of the DBWR process is to keep the buffer
cache “clean” by writing dirty buffers to disk.

▪ Log Writer Process (LGWR)


• The log writer process (LGRW) writer the redo log file on disk
.
• LGWR writer one contiguous portion of the buffer to disk
,LGWR writer a commit record when a user process commits a
transaction.
▪ Recoverer Process (RECO)
• The recoverer process(RECO)is a process used with the
distributed option that automatically resolve failures involving
distributed transaction .
• The remote server is not available or the network connection
has not been re-established ,RECO automatically tries to
connect again a timed interval .
▪ Checkpoint Process (CKPT)

348 Oracle 11g/12c


By:Mr.Krishna Reddy DURGASOFT

• When a checkpoint occurs ,oracle must update the header of all


data files to record the details of the checkpoint .this is done by
CKPT.
▪ Process Monitor(PMON):
• The process monitor(PMON) performs process recovery when
user process fails.
• PMON is responsible for cleaning up the cache and freeing
resources that the process was using.
Ex: Its resets the status of the active transaction table , release locks.
▪ Snapshots Refresh processes(Snpn):
• With the distributed option ,up to ten snapshots refresh
process(SNP0....SNP9) can automatically refresh table
snapshots.
• These process wake up periodically and refresh any snapshot
that are scheduled to be automatically refreshed.
▪ System Monitor(SMON):
• The system monitor process perform instance recovery at
instance startup.
• SMON is also responsible for cleaning up temporary segment
that are no longer in use.
▪ Data Files:
• This mandatory disk component is used for oracle dictionary
and application database object.
• data files stores oracle data.
• Each data file can be associated with only one database.
▪ Redo logs:
• This mandatory Disk component is used for storing redo
information on disk(IC rollback segment data).
▪ Control File:
• The physical location of both data files and redo locks in the
server's files system are stored in your control file.
▪ Parameter Files(init.ora) :
• This mandatory disk component is used for configuring how
oracle operates while it is running.

Mr.Krishna Reddy

349 Oracle 11g/12c

You might also like