Introduction To PL/SQL: Kristian Torp
Introduction To PL/SQL: Kristian Torp
Kristian Torp
daisy.aau.dk
1 Introduction
2 Stored Procedures
An Overview
Data Types
Parameter Parsing
Cursors
3 Packages
Case Study: Table API
4 Summary
Learning Outcomes
Understand how code can be executed within a DBMS
Be able to design stored procedures in general
Be able to construct and execute stored procedures on Oracle
Knowledge about the pros and cons of stored procedures
Note That
Concepts are fairly DBMS independent
All code examples are Oracle specific
SQL
Knowledge about the SQL select statement
Knowledge about SQL modification statements, e.g., insert and delete
Knowledge about transaction management, e.g., commit and rollback
Knowledge about tables, views, and integrity constraints
Purpose
Move processing into the DBMS from client programs (database
applications)
Advantages
Code accessible to all applications
Access from different programming languages
Very efficient for data intensive processing
Process large data set, small result returned
Enhance the security of database applications
Avoid SQL injection attacks
http://en.wikipedia.org/wiki/SQL_injection
Missing Standard
Unfortunately, the major DBMS vendors each have their own SQL dialect
Kristian Torp (Aalborg University) Introduction to PL/SQL November 30, 2009 6 / 55
Overview
SQL extended with control structures
Control structures like if and loop statements
Used for
Stored procedures (and functions)
Package
Triggers
Focus
The focus is here on stored procedures and packages!
Kristian Torp (Aalborg University) Introduction to PL/SQL November 30, 2009 7 / 55
Motivation for Stored Procedures
Note
This is not different from any other procedural programming language!
c r e a t e o r r e p l a c e procedure h e l l o w o r l d i s
begin
dbms output . p u t l i n e ( ’ H e l l o , World ! ’ ) ;
end ;
Note
It is a procedure, i.e., not a function
It is a begin and end language, not curly brackets: { and }
It uses a built-in library dbms output.put line
The package dbms output has the procedure put line
Note
It is a function, i.e., has a return statement
It takes parameters height and weight
It is strongly typed language, i.e., parameters and the return value
Kristian Torp (Aalborg University) Introduction to PL/SQL November 30, 2009 12 / 55
Executing Stored Procedures
−− t o enable o u t p u t from t h e s e r v e r
SQL> s e t s e r v e r o u t p u t on
−− execute t h e procedure
SQL> execute h e l l o w o r l d ;
−− execute t h e f u n c t i o n
SQL>exec bmi ( 1 . 8 7 , 9 0 ) ;
−− r e s u l t s i n an e r r o r , v a l u e r e t u r n e d by f u n c t i o n must be used !
−− Wrap t h e f u n c t i o n c a l l
SQL>exec dbms output . p u t l i n e ( bmi ( 1 . 8 7 , 9 0 ) ) ;
Note
Output from server is not enabled by default in a session!
Return value of a function cannot be ignored!
Kristian Torp (Aalborg University) Introduction to PL/SQL November 30, 2009 13 / 55
Using SQL in Stored Procedures
c r e a t e o r r e p l a c e f u n c t i o n g e t s t a t u s ( s t u d e n t i d number )
r e t u r n varchar2 i s
v s t a t u s varchar2 ( 5 0 ) ;
begin
s e l e c t s t a . dsc
into v status
from s t u d e n t stu , s t a t u s s t a
where s t u . s t a t i d = s t a . s t a t i d
and stu . sid = student id ;
return v status ;
end ;
Note
The declaration of the variable v status
The usage of the into keyword in the select statement
The usage of the parameter student id in the select statement
Caller
c r e a t e o r r e p l a c e procedure c a l l p i s
begin
p ( ’ H e l l o ’ ) ; p ( ’ World ! ’ ) ;
end ;
Note
Can call own and built-in stored procedures
Will use the procedure p instead of dbms output.put line
You are now officially a PL/SQL library builder!!!
Kristian Torp (Aalborg University) Introduction to PL/SQL November 30, 2009 15 / 55
Control Structures: A Crash Course I
c r e a t e o r r e p l a c e procedure pb ( v a l boolean ) i s
begin
i f v a l = t r u e then
dbms output . p u t l i n e ( ’ t r u e ’ ) ;
e l s i f v a l = f a l s e then
dbms output . p u t l i n e ( ’ f a l s e ’ ) ;
else
dbms output . p u t l i n e ( ’ n u l l ’ ) ;
end i f ;
end ;
Note
Is this stupid?
Recall three-valued logic the root of all evil!
We will use the procedure pb in the code that follows!
c r e a t e o r r e p l a c e procedure count 10 i s
i i n t := 1;
begin
w h i l e i < 10 l o o p
dbms output . p u t l i n e ( i ) ;
i := i + 1;
end l o o p ;
Note
What is printed 1 to 9 or 1 to 10?
PL/SQL also has a for statement, very different from C
PL/SQL does not have increment/decrement operators, e.g., i −− or ++j
PL/SQL does not have compound assignments, e.g., i +=7 or j ∗=2
Output
A string
36893488147419103232
115904311329233965478,149216911761758199
Note
Forget what you think of data types and size!
Very high precision on all number types in both SQL and PL/SQL
The size of strings must be defined
Kristian Torp (Aalborg University) Introduction to PL/SQL November 30, 2009 20 / 55
Overview: Scalar Data Types
create or r e p l a c e procedure u s i n g d e c i m a l i s
v dec decimal ( 4 , 2 ) ;
begin
v dec := 12.34;
dbms output . p u t l i n e ( v dec ) ;
v dec := 12.344;
dbms output . p u t l i n e ( v dec ) ;
v dec := 12.347;
dbms output . p u t l i n e ( v dec ) ;
end ;
Questions
Will this compile, note that it is decimal(4,2)?
What will be printed (if it compiles)?
Are you surprised?
Description Type
Record
Composite Varray
Table
BLOB
Large Objects CLOB
BFILE
REF
Reference Types
REF CURSOR
Note
We will only use records in this lecture.
Note
The anchored type using the %type
Very convenient of maintenance reasons (avoid “hard-wiring” types)
Widely used, you are encouraged to use it!
c r e a t e o r r e p l a c e procedure p i n o u t ( v a l i n o u t i n t ) i s
begin
val := val + 5;
end ;
c r e a t e o r r e p l a c e procedure c a l l p s i s
v in i n t := 10;
v i n o u t i n t := 10;
begin
p in ( v in ) ; p( v in ) ;
p in out ( v in out ) ; p( v in out ) ;
end ;
Questions
What are the formal parameter(s)?
What are the actual parameter(s)?
Is it call-by-value or call-by-reference?
c r e a t e o r r e p l a c e procedure g e t x y c o o r (
c o o r i d i n i n t , x coor out i n t , y coor out i n t )
is
begin
x c o o r : = round ( c o o r i d / 4 . 2 ) ; −− s t u p i d c a l c u l a t i o n s
y c o o r : = round ( c o o r i d / 7 . 5 ) ;
end ;
Note
in and out parameters can both be used in same procedure
The out parameters are write-only
More than one value is “returned” by the procedure
The calculation is naturally plain stupid
round is the built-in rounding function
Mode Description
in Formal parameter is read-only
out Formal parameter is write-only
in out Formal parameter is read-write
Note
in is the default parameter mode if the mode is not specified
Stored procedures cannot be overloaded on the parameter signature
There is a nocopy compiler hint for in out parameters
Definition
A cursor is a mechanism that ensure a result set can be identified by a
declarative language such as SQL and processed by a procedural
language such as PL/SQL or C#
Solution
Solves the well-known impedance mismatch problem!
Generality
Knowledge about cursors in PL/SQL is directly transferable to many other
programming languages.
Note
The view tab is a table that contains all table names
The cursor is declared, opened, fetched, and closed
Kristian Torp (Aalborg University) Introduction to PL/SQL November 30, 2009 36 / 55
Cursor Attributes
Note
There are additional attributes for bulk operations.
c r e a t e o r r e p l a c e procedure l s c n t i s
cursor c tables i s
s e l e c t table name from c a t ;
v t a b le n a m e c a t . table name%t y p e ;
begin
open c t a b l e s ;
loop
f e t c h c t a b l e s i n t o v t a b le n a m e ;
e x i t when c t a b l e s%n o t f ou n d ;
p ( c t a b l e s%rowcount | | ’ ’ | | v t a b le n a m e ) ;
end l o o p ;
close c tables ;
end ;
What is printed?
c r e a t e o r r e p l a c e procedure l s i s o p e n i s
cursor c tables i s
s e l e c t table name from c a t ;
v t a b le n a m e c a t . table name%t y p e ;
v s t a t u s boolean : = f a l s e ;
begin
v s t a t u s : = c t a b l e s%isopen ; pb ( v s t a t u s );
open c t a b l e s ;
v s t a t u s : = c t a b l e s%isopen ; pb ( v s t a t u s );
loop
f e t c h c t a b l e s i n t o v t a b le n a m e ;
e x i t when c t a b l e s%n o t f ou n d ;
end l o o p ;
v s t a t u s : = c t a b l e s%isopen ; pb ( v s t a t u s );
close c tables ;
v s t a t u s : = c t a b l e s%isopen ; pb ( v s t a t u s );
end ;
What is printed?
Goal
To build a uniform way to address the data stored in table!
Name Description
exist(<primary key>) Return true if primary key exists
to string(<primary key>) Return string representation of row
print(<primary key>) Convenient way to display a row
Note
Many more methods can be envisioned
Think object-relational mapping (ORM) tools
c r e a t e o r r e p l a c e package ccourse i s
f u n c t i o n e x i s t ( c i d course . c i d%t y p e ) r e t u r n boolean ;
f u n c t i o n t o s t r i n g ( c i d course . c i d%t y p e ) r e t u r n s t r i n g ;
procedure p r i n t ( c i d course . c i d%t y p e ) ;
end ;
Note
The header lists all the public stored procedures
The naming convention table name course package name ccourse
The design is influenced by the Object class from Java and C#
Quiz
Why is the method called exist and not exists?
Note
Uses the private method check valid cid to check preconditions
Uses the private cursor cur exist
Returns true if a valid primary key is found
f u n c t i o n t o s t r i n g ( c i d course . c i d%t y p e ) r e t u r n s t r i n g i s
v rv string (512);
r e c e x i s t c u r e x i s t%rowtype ;
begin
c h e c k v a l i d c i d ( c i d ) ; −− p r e c o n d i t i o n
open c u r e x i s t ( c i d ) ;
fetch cur exist into rec exist ;
close c u r e x i s t ;
v r v : = ’ course name : ’ | | r e c e x i s t . cname | | ’ ’ | |
’ course desc : ’ | | r e c e x i s t . dsc ;
return v rv ;
end ;
Note
Uses the private method check valid cid to check preconditions
Uses the private cursor cur exist
print calls to string
SQL> s e t s e r v e r o u t p u t on
−− execute t h e procedure
SQL> execute ccourse . p r i n t ( 4 ) ;
Note
Similar to executing a stored procedure
Access member by the dot notation
Note
Results in an error “ORA-20001: Course ID is null”
www.oracle.com/technology/tech/pl_sql/index.html
PL/SQL’s home
www.psoug.org/library.html A very good and complete wiki with
PL/SQL information
plsql-tutorial.com/ A crash course covering many PL/SQL
features
en.wikibooks.org/wiki/Oracle_Programming/SQL_Cheatsheet
A short overview of PL/SQL
www.java2s.com/Tutorial/Oracle/CatalogOracle.htm Many
good examples, too many commercials