updated_PLSQL
updated_PLSQL
PL/SQL
Introduction to PL/SQL
SQL does not have any procedural
capabilities such as looping and
branching nor does it have any
conditional checking capabilities vital for
data testing before storage.
For this, Oracle provides PL/SQL.
Programmers can use it to create
programs for validation and manipulation
of table data.
PL/SQL
PL/SQL is basically an extension of SQL. It has:
Improved Performance
Enhanced Productivity
Portability
DECLARE
fname varchar2(30);
lname varchar2(30);
Counter number :=0;
Anchored data type
Declarations
%TYPE declaration attribute
to anchor the datatype of one
variable to another data structure,
such as a PL/SQL variable or a column
in a table.
When you anchor a datatype, you tell
PL/SQL to set the datatype of one
variable from the datatype of another
element.
Anchored data type
Declarations
The syntax for an anchored datatype
is:
<variable name> <type attribute>
%TYPE [optional default value
assignment];
where <variable name> is the name
of the variable you are declaring and
<type attribute> is Table column in
format "table.column"
Anchored data type
Declarations
Executable Section
Begin
End;
Exception Handling Section
An error condition during a program execution is called
an exception in PL/SQL
There are two types of exceptions:
System-defined exceptions
User-defined exceptions
Syntax:
EXCEPTION
WHEN exception1 THEN exception1-handling-statements
WHEN exception2 THEN exception2-handling-statements
WHEN others THEN exception3-handling-statements END
System-defined exceptions
System-defined exceptions are raised by database
server automatically whenever there is any
internal database error
E.g.
Exception
When No_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘ There is no student
with ‘ || ‘ student id 123 ‘ );
End;
Exceptions can be used explicitly by programmer
by using Raise command
User-defined Exceptions
PL/SQL allows to define your own exceptions as per
the need of your program
User defined exceptions must be declared and then
raised explicitly using raise command
Syntax:
DECLARE ex_invalid_id EXCEPTION;
BEGIN if condition then
raise ex_invalid_id;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
End;
PL/SQL examples
Example 1: find record from
student table
SQL> create table student(SID number, FIRSTNAME varchar2(20), LASTNAME
varchar2(20));
SQL> desc student;
Name Null? Type
----------------------------------------- -------- ----------------------------
SID NUMBER
FIRSTNAME VARCHAR2(20)
LASTNAME VARCHAR2(20)
DECLARE
vnum number;
vresult number;
Begin
vnum:= :num;
vresult := power(vnum,2);
Dbms_output.put_line('result is ' || vresult);
End;
Example 3: Determine day of week
based on today's date
Declare
V_day varchar2(20);
Begin
V_day:=to_char(sysdate,'day');
Dbms_output.put_line('Today is :' || v_day);
End;
Conditional Control statements
If – then statement
If – then – else statement
ELSIF statement (nested if else
statement)
IF-THEN Statements Start IF
If Condition then
Statement1; is
………………….
Statement n;
End if Execute statements
End IF
Next stmt
IF-THEN example
Declare
V_num1 number:=5;
V_num2 number:=3;
V_temp number;
Begin
If v_num1>v_num2 then
V_temp:= v_num1;
V_num1:=v_num2;
End if;
Dbms_output.put_line('num1 is :' || v_num1);
Dbms_output.put_line('num2 is :' || v_num2);
End;
IF-THEN-ELSE
Start IF
If condition then
Stmt1; Y Is
Cond
N
true
Else
Stmt2 Execute
Execute
stmt1
stmt2
End if
Stmt3; End if
Next stmt
IF-THEN-ELSE Example
Declare
V_num number:= :v_num;
Begin
If mod(v_num,2)=0 then
Dbms_output.put_line(v_num|| ' is even no');
else
Dbms_output.put_line(v_num|| ' is odd no');
End if;
Dbms_output.put_line('done');
End;
ELSIF
If condition1 then
Stmt1;
Elsif condition2 then
Stmt2;
Elsif condition3 then
Stmt3;
Else
Stmt n;
End if;
ELSIF example
Declare
vnum number := :v_num;
Begin
If vnum<0 then
Dbms_output.put_line(vnum|| ' is –ve no');
Elsif vnum=0 then
Dbms_output.put_line(vnum|| ' is equal to 0');
else
Dbms_output.put_line(vnum|| ' is +ve no');
end if;
end;
Iterative Control statements
Simple loop
Exit statement
While loop
For loop
Simple Loop
Loop
Stmt1; Start loop
Stmt2;
Stmt N;
End loop;
Execute stmts
Example:
Loop End loop
ctr:= ctr + 1;
IF ( ctr > 5) THEN
END IF;
END LOOP;
Exit
Loop
Start loop
Stmt1; No
Stmt2;
If condition then Execute stmt
Exit;
End if;
Is exit condn
End loop; true
Example: yes
LOOP
ctr:= ctr + 1; Exit loop
EXIT WHEN ctr > 5;
END LOOP;
Next stmt
Simple loop example
Declare
counter number:=0;
Begin
Loop
counter:=counter+1;
Dbms_output.put_line('counter = ' || counter);
Exit when counter>=5;
End loop;
End;
Simple loop example
Output:
counter = 1
counter = 2
counter = 3
counter = 4
counter = 5
Statement processed.
WHILE LOOP
WHILE cond loop
stmt1; No
Is condn true
stmt2;
………….. Yes
Next stmt
While Loop example
Declare
v_counter number:=5;
Begin
While v_counter>0 loop
Dbms_output.put_line('v_counter:' || v_counter);
v_counter:=v_counter-1;
End loop;
dbms_output.put_line('done');
End;
While Loop example
Output:
v_counter:5
v_counter:4
v_counter:3
v_counter:2
v_counter:1
done
Statement processed.
For Loop
For loop_counter IN [REVERSE] lower_limit..upper_limit
loop
Initialize counter
stmt1;
stmt2;
………… Is counter
bet lower &
StmtN; Upper
limits
end loop;
yes
No
Exeute stmt
Increment counter
Next stmt
For Loop example
Begin
For v_counter IN 1..5 loop
Dbms_output.put_line('v_counter' || v_counter);
End loop;
End;
v_counter 1
v_counter 2
v_counter 3
v_counter 4
v_counter 5
Statement processed.
For Loop example
Begin
For v_counter in reverse 1..5 loop
Dbms_output.put_line('v_counter' || v_counter);
End loop;
End;
v_counter 5
v_counter 4
v_counter 3
v_counter 2
v_counter 1
Statement processed.
PL/SQL DATABASE OBJECTS
Pl/SQL database objects
Procedures
Functions
Triggers
Cursor
Functions
These subprograms return a single
value, mainly used to compute and
return a value.
A function must return a value back
to the caller. A function can return
only one value
Function Syntax
Declare
Local_first_name varchar2(50);
Local_last_name varchar2(50);
Begin
find_sname(1,Local_first_name,Local_last_name );
Dbms_output.put_line(Local_first_name);
Dbms_output.put_line(Local_last_name);
End;
Trigger
Trigger is a named PL/SQL block stored
in a database and executed implicitly
when a triggering event occurs.
Triggering event is a DML statement
executed against database table.
Trigger can fire before or after a
triggering event.
To check triggers in database
SELECT * FROM user_triggers;
Uses of database Triggers
It provides a highly customizable database
management system
A trigger can permit DML statements against a
table only if they are issued, during regular
business hours or on predetermined weekdays
It can be used to keep an audit trail of the table
It can be used to prevent invalid transactions
Enforce complex security authorization
Database Triggers V/S
Procedures
Triggers do not accept parameters
whereas procedures can
A triggers is executed implicitly by the
oracle engine itself upon modification
of an associated table or its data
To execute a procedure, it has to be
explicitly called by a user
Types of Triggers
A Row trigger: fires once for each row
affected. It uses FOR EACH ROW clause.
Statement Trigger: fires once, irrespective
of number of rows affected in the table.
Combination trigger:
Before statement trigger
Before row trigger
After statement trigger
After row trigger
Types of Triggers
Before and after Triggers
While defining the trigger we can specify whether to
perform the trigger action (i.e. execute trigger body)
before or after the triggering statement. BEFORE and
AFTER triggers fired by DML statements can only be
defined on tables.
Trigger created.
Trigger Example 2
select * from student;
SID FIRSTNAME LASTNAME MARKS
1 seema patil 150
2 pooja kamat -
3 kavita buchade 160
declare
vname varchar2(20);
begin
select firstname into vname from student;
dbms_output.put_line('name is ' || vname);
end;
ORA-01422:
exact fetch returns more than requested number of rows
Cursor Example 1
Declare Cursor student1 is
Select firstname from student;
Vname student.firstname%type;
Begin
Open student1;
Loop
Fetch student1 into vname;
Exit when student1%notfound;
Dbms_output.put_line('Student name is ' ||
vname);
End loop;
Close student1;
end;
Output: Student name is seema
Student name is pooja
Student name is kavita
Statement processed.
Cursor Example 2
Declare Cursor student1 is
Select firstname, marks from student;
Vname student.firstname%type;
student_marks student.marks%type;
Begin
Open student1;
Loop
Fetch student1 into vname,student_marks;
Exit when student1%notfound;
Dbms_output.put_line('Student name is ' || vname ||' and marks: ' ||
student_marks);
End loop;
Close student1;
end;
Cursor Example 2: Output
Student name is john and marks: 800
Student name is amit and marks: 700
Student name is sumit and marks: 390
Student name is neil and marks: 300
Student name is smith and marks: 500
Student name is bob and marks: 600
Student name is xyz and marks: 400
Statement processed.
Cursor Example 3
create table emp(empno number(4,0),ename
varchar2(10),job varchar2(9),mgr number(4,0),hiredate
date, sal number(7,2), comm number(7,2),deptno
number(2,0));