Oracle SQL plsql-264-349
Oracle SQL plsql-264-349
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.
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.
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.
NULL block.
SQL> BEGIN
RETURN;
END;
→BLOCK with RETURN clause.
SQL>DECLARE
BEGIN
NULL;
END;
SQL>DECLARE
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;
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.
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.
DEFAULT
• Sets the default value for the value in the PL/SQL program if not
attended.
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;
SQL> BEGIN
DBMS_OUTPUT.PUT_LINE('The sum of Frist and Second num is
'||(&FirstNum+&SecondNum));
END;
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;
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
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;
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.
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;
IF…THEN…ELSE…END IF statement
SQL>DECLARE
v_Num NUMBER:=&Enternumber;
BEGIN
IF MOD(v_Num,2)=0 THEN
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
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.
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;
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');
SQL>DECLARE
v_Dname varchar2(20);
v_Deptno number;
BEGIN
SELECT deptno into v_Deptno
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>DECLARE
a Number:=100;
BEGIN
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.
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
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.
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;
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;
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;
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
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).
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.
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;
Opening a Cursor:
Syntax:
OPEN cursor_name;
Syntax:
1) FETCH cursor_name INTO list_of_variables;
2) FETCH cursor_name INTO PL/SQL_record;
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.
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;
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
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;
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’)
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;
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;
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;
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;
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;
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
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.
Types of Exception
>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;
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:
Step
1. Declare Exception
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);
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.
• 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
• 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
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;
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.
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
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;
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;
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
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;
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.
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
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)
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);
END;
SQL>DECLARE
n NUMBER:=&no;
BEGIN
proc_sc(n,:sr,:cr);
display('The '||n||' seq and cube values are '||:sr||' '||:cr);
END;
.
> 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.
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.
MILLER
SQL>exec sci(1000,12,2)
Note: Synonym can’t be created for Procedure which is defined in
Package.
pragma autonomous_transaction
END add_dept;
Dropping Procedure
• Similar to dropping a table procedure can also be dropped.
Syntax
SQL> DROP PROCEDUE procedure_name;
Illustration
SQL>DROP PROCEDURE cal_intr;
/
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;
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.
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
Application Trigger
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.
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 :new and :old records can be referenced inside trigger_condition as well.
• The colon is only valid in the trigger body.
• Activated when table are manipulated from other application software also.
Database
Applications
Table
Update Update Trg
….
….
Insert
…. Insert Trg
….
Delete
…. Delete Trg
Table Level
END trg_upp_con;
Table delete_log
ecode NUMBER(4),
ename VARCHAR2(20),
basic NUMBER(7,2),
dod timestamp
Table Trace
-----------------
Userid varchar2(20),
dod timestamp
[DECLARE]
BEGIN
IF Inserting THEN
SQL Statements
END IF;
IF updating THEN
SQL Statements
END IF;
IF deleting THEN
SQL Statements
END IF;
END [trg_name];
Table job_list
Remove trigger
Syntax
SQL>DROP TRIGGER <trg_name>;
SQL>DROP TRIGGER trg_wht;
This trigger tracks the creation all objects, including which user issued the
CREATE statement.
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.
Components of a Package
--Specification
--Body
Application Database
Package
Specification
Body
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
Bodiless Package
• We can declare Package Specification that does not need Package body.
BEGIN
RETURN(pbasic+pbasic*0.45+pbasic*0.35-pbasic*0.15);
END gross;
END pack_eg;
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;
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;
(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 ;
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 :-
Oracle Architecture:
Snpn
PMON
Private
Redo Log buffer
Buffer Cache
Redo
ARCH Logs
Data1.dbf
Data2.dbf
Data3.dbf
init.ora
Control File
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 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
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 :
▪ 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.
Mr.Krishna Reddy