You are on page 1of 16

introduction to pl/sql

■ objectives :
–list the limitations of sql
–describe the need for pl/sql
–list pl/sql features
–list advantages of pl/sql
–list pl/sql character set, operators, symbols and data
types
–explain what is a variable
–describe variable declaration
–state variable naming rules
–explain what is constant
–describe pl/sql program structure
–construct a pl/sql block

sql : summary
■ sql
–the most powerful & comprehensive database language
■you can create, organise, retrieve and maintain data using sql
–flexible
and efficient language designed to manipulate
and examine relational data
–4 gl
■insulatesuser from data structure & algorithms
■describes what to do and not, how to do it
–but it does not provide programming language
features

the solution to sql’s limitations


■ the solution
–extending sql by adding procedural language features
–oracle pl / sql
■oracle’s
procedural language extension to the non-procedural
sql
■combines data manipulation power of sql & procedural power of
standard programming languages
pl/sql
■ pl/sql features:
–allowsyou to define and use, variables and constants
–provides contructs to control the flow of a program
■branching / conditional contructs
■iterative / looping contructs
–you can do row by row processing of data retrieved from
data base using cursors
–you can trap errors and write routines to handle pre-
defined and user-defined error situations
–write modular application by dividing it into
■sub programs (procedures and functions )
■packages
■triggers

advantages of pl / sql
■support for sql :
–supports all the functionalities of sql
–efficient database handling
■improved performance :
–sql processing: single statement
–pl/sql processing: block of statements
■reduces overheads
■improves performance
■block structure :
–pl/sql is a block structured language
–programs can divided into logical blocks of code
■higher productivity :
–procedural constructs
–pl/sql can be used with
■oracle database server
■oracle tool like forms, reports etc.
■common programming language for back-end and front-end
■portability :
–applications written in pl/sql are portable to
■any computer hardware
■any os environment
where oracle rdbms is running
pl/sql language
■character set
■reserve words

■arithmetic operators

■relational operators

■special operators

■logical operators

■miscellaneous symbols

pl/sql character set


■ characters :
–alluppercase & lowercase letters a-z, a-z
–digits 0-9
–white space, tab & carriage return
–symbols
■( ) + - */ < > = ! ~ ; : . ‘ @ % , “ # $ ^ & _ | { } ? [ ]

pl/sql operators
■ arithmetic operators :
operator meaning
+ addition
* multiplication
** exponentiation
- subtraction
/ division

■ relational operators :
operator meaning
<>, ^=, != not equal to
> greater than
< less than
= equal to
>= greater than or equal to <=
less than or equal to
■ special operators
–is null
–like
–between
–in

■ logical operators
–not
–and
–or

■ miscellaneous symbols :
–( ) lists separators :
■e.g. name in (‘sameer’, ‘rajiv’, ‘amit’)

–; end of statement :
■e.g. procedure_name (arg1, arg2);

–‘’ character string enclosure


■e.g. if var_name = ‘seema’ ...

–. item separator
■e.g. select <col_list> from schema.table_name …. ;
–:= assignment
■e.g. rec_no := rec_no+1;
–|| concatenation
■e.g. full_name := ‘sameer’ || ‘agashe’;
–-- comment delimiter
■e.g. -- this is a comment

–/* and */ comment delimiter


■e.g. /* this is also a comment */
pl/sql data types
■a pl/sql program is written to manipulate different
types of data
■data type used could be
–oracle data type
– pl/sql data type
■ number :
–zero, positive and negative numbers
■ number (p,s) :
–number with precision & scale specified
■ binary_integer :
–signed integers ranging from -2147483648 to
2147483647
■ boolean :
–stores the values true or false
■ char (size) :
–fixed length string of maximum 32767 characters
■ varchar2 (size) :
–variable length string maximum 32767 characters
■ date :
–stores the date & time data
■ rowid :
–same as oracle rowid data type

■ other data types :


–%rowtype
–%type
–record
variables
■variable
–named data item
–has a name and data type
–used to store the results of a query or calculations
–declared in the declaration section of pl/sql block

■syntax :
<var_name> <data_type> [not null] [:=<value>];

variables naming rules


–variable name
■must start with a letter (an alphabet) (a-z), (a-z)
■optionally followed by one or more letters, numbers (0-9) or
■or the special characters $, # or _
–variablename can have maximum 30 characters
–there can be no spaces embedded in the variable name
–you can not use reserved words as a variable name
–example: declaring variables
mgrname char(20);
age number (3);
deptno number (2):=30;
temp_name emp.ename%type;

assigning values to a variable


■examples :
open_date := sysdate;

annual_sal := (sal*12) + 12* nvl(comm, 0);


flag := true;

flag := not flag;

constants
■values that do not change during program execution
■declaration is same as variable declaration except

keyword constant
■syntax :
<const_name > constant <data type> :=<value>;
■constants must also be initialized
■examples :
pin_code constant number (6) := 411002;
pi constant number (4,3) := 3.142;
category constant varchar (25) default ‘executive’;

pl/sql program structure


■ pl/sql block
–isthe basic unit of a pl/sql program
–consists of a set of sql or pl/sql statements
–performs a single logical function

■ the pl/sql block structure


declare
declarative section
begin
executable section
exception
exception handing section
end;

■ pl /sql block
–the declarative & the exception handling section are
optional
–the executable section is mandatory
–a block can have any number of nested blocks defined
within its executable section
–a nested block is called as sub block
the declarative section
■ used for declaring
–variables, constants
–cursors
–definition of errors : exceptions
■ declaring objects allocates storage space to it

the executable section


■executable part of pl /sql block , mandatory section
■contains sql and pl /sql statements for querying

and manipulating data


■there must be at least one executable statement

■when there is no executable statement you can use

null statement

the exception handling section


■conditions that lead to error are known as
exceptions
■you can take care of exceptions by writing exception

handlers

writing pl/sql code


1. insert a new employee rajesh with employee
number 4321 in department 20.
solution :
declare
v_empno number (4) := 4321;
v_ename emp.ename%type := ‘rajesh’;
v_deptno number (2) := 20;
begin
insert into emp (empno, ename, deptno)
values (v_empno, v_ename, v_deptno);
end;

2.update the commission of an employee number


7369 to 500, if it is null; otherwise raise his
commission by 25%.

■ solution :
–use of select … into … statement
–use of if ... then … else statement
decalre
v_empno number (4) := 7369;
v_comm emp.comm%type;
begin
select comm into v_comm from emp
where empno = v_empno;
if v_comm is null then
v_comm := 500;
update emp set comm = v_comm
where empno = v_empno;
else
v_comm := v_comm *1.25;
update emp set comm = v_comm
where empno = v_empno;
end if;
commit;
end;

variable scope & visibility


■ variable scope
–thescope of a variable is the portion of a program in
which the variable can be accessed
■ visibility
–the visibility of a variable is the part of the program in
which it can be accessed without qualifying the
reference
<<outer_block>>
declare -- outer block begins here
v_ename emp.ename%type;
v_empno emp.empno%type;
begin
{ v_ename & v_empno are in scope & are visible here }
<<inner_block>>
declare -- inner block begins here
v_empno number (4);
v_hiredate date;
begin
{ v_ename from outer_block,
v_empno & v_hiredate from inner_block are in scope & visible }
{ v_empno from outer_block is in scope but not visible }
{ v_empno from outer_block can be referenced using
outer_block.v_empno :=1234;}
end inner_block; -- inner block ends here
{ v_empno, v_hiredate from inner_block have lost their scope hence not visible}
{ v_empno, v_ename from outer_block are still in scope hence visible}
end outer_block; -- outer block ends here
{ v_empno, v_ename from outer_block have also lost their scope}

use of built-in functions in pl/sql


■ the following type of functions are valid in pl /sql
–single-row number function
–single-row character function
–date functions
–conversion functions
■ group functions such as
–min, max, sum, avg, count are not valid in pl/sql

pl/sql control structures


■ objectives :
–state the need of control structures
–state the syntax & use of conditional constructs
–state the syntax & use of loop constructs
–state the syntax & use of sequential constructs and their
restrictions
–construct pl/sql programs using control structures

■they control the sequence of execution of statements in a


program
■control structures are also known as programming
constructs
■programming constructs supported by pl/sql are :
–conditional constructs
–iterative
constructs
–sequential constructs

conditional constructs :
■checks for the validity of a condition and accordingly
performs a corresponding action
■syntax :
if <condition> then
<statements>
[ elsif <condition> then
<statements> ]
...
[ else
<statements> ]
end if;

■ syntax 1 :
if <condition> then
<statements>
end if;
■ e.g.
if v_sal > 5000 then
v_comm := v_sal *.15;
end if;

■ syntax 2 :
if <condition> then
<statements>
[ else
<statements> ]
end if;
■ e.g.
if v_sal > 5000 then
v_comm := v_sal *.15;
else
v_comm := v_sal *.20;
end if;

■ syntax 3 :
if <condition> then
<statements>
[ else
if <condition> then
<statements>
end if; ]
end if;

conditional constructs :
■ example. 1 : for empno 7869
a) if his salary is less than 3000 then raise the
commission by 15% of salary,
b) if his salary is between 3000 and 5000 then raise the
commission by 200 + 12% of salary,
c) otherwise raise the commission by 500 + 10% of salary.
declare
v_empno number(4) := 7869;
v_comm emp.comm%type;
v_sal emp.sal%type;
begin
select sal, comm into v_sal, v_comm from emp
where empno = v_empno;
if v_sal < 3000 then
v_comm := v_comm + v_sal * .15;
elsif v_sal <= 5000 then
v_comm := v_comm + 200 + v_sal * .12;
else
v_comm := v_comm + 500 + v_sal * .1;
end if;
update emp set comm = v_comm
where empno = v_empno;
end;

iterative constructs :
■iterative constructs execute a sequence of
statements repeatedly
■iterative constructs in pl/sql are
–loop
–while - loop
–for – loop

■simplest iterative construct


■syntax :
loop
<statements>
end loop;
■loop construct does not have facility to check for a condition
■infinite loop
■exit statement can be used to exit the loop

■ exiting loop using exit statement :


loop
<statements>
if <condition> then
exit ;
end if;
end loop;

e.g. :
loop
v_counter := v_counter + 1;
...
if v_counter > 50 then
exit;
end if;
end loop;

loop construct
exiting loop using exit when :
–condition can be specified with exit statement itself

loop
<statements>
exit when <condition>;
end loop;

■ e.g. :
loop
insert into temp ……..
v_counter := v_counter + 1;
exit when v_counter > 50;
end loop;

while - loop
■a while - loop is condition driven
■loop is executed as long as condition evaluates to

true
■syntax :
while <condition> loop
<statements>
end loop;
for - loop
■executes a set of statements specified no. of times.
■syntax :
for <counter> in [reverse] lowerbound .. upperbound
loop
<statements>
end loop;

■ example 1 :
for v_counter in 1..50 loop
insert into ….
:
end loop;

■ example 2 :
for v_counter in reverse 1..50 loop
insert into…..
:
end loop;

nested loops
you can have nesting to any number of loops
■labeling loop to identify them

■exit statement with label

label
■undeclared identifier
■label name placed before loop or

for … loop keyword


■can exit using exit and label

■syntax : exit label_name;

■ e.g. : exit inner_loop;


sequential constructs
■goto
■null

■ goto :
–transfers control to a label unconditionally
–not to be used normally
declare
v_counter binary_integer := 1;
begin
loop
insert into temp
values (v_counter, ‘loop index’);
v_counter := v_counter + 1;
if v_counter > 50 then
goto end_loop;
end if;
end loop;
<<end_loop>>
null;
end;

restrictions on goto statement


■ a goto statement can not branch into the following
destination
–an if statement
–a loop statement
–a sub - block

:
if
:
end if;

:
loop
:
end loop;

begin -- outer block


:
begin 2 -- inner block
:
end;
end;

■a goto can’t branch from one if statement to


another
■a goto can’t branch out of sub-program

■ e.g. 1 if
:
end if;
:
if
:
end if;
■a goto statement can’t branch from an exception

handler into the executable section.


declaration
:
begin
:
exception
:
end
null statement
■signifies a state of inaction
■place holder

■passes execution to next statement

■use
–improves readability
–if there are no executable statements, used to create
dummy sub programs for testing

You might also like