Introduction to PL/SQL - torp/Oracle/introduction_to_plsql.pdf · PDF fileIntroduction to...

Post on 01-Feb-2018

228 views 0 download

Transcript of Introduction to PL/SQL - torp/Oracle/introduction_to_plsql.pdf · PDF fileIntroduction to...

Introduction to PL/SQL

Kristian Torp

Department of Computer ScienceAalborg University

www.cs.aau.dk/˜torptorp@cs.aau.dk

December 2, 2011

daisy.aau.dk

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 1 / 56

Outline

1 Introduction

2 Stored ProceduresAn OverviewData TypesParameter ParsingCursors

3 PackagesCase Study: Table API

4 Summary

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 2 / 56

Outline

1 Introduction

2 Stored ProceduresAn OverviewData TypesParameter ParsingCursors

3 PackagesCase Study: Table API

4 Summary

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 3 / 56

Learning Outcomes

Learning OutcomesUnderstand 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 ThatConcepts are fairly DBMS independent

All code examples are Oracle specific

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 4 / 56

Prerequisites

SQLKnowledge 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

Procedural Programming LanguageKnowledge about another programming language of the C family

Knowledge about data types, e.g., int, long, string, and Boolean

Knowledge of control structures, e.g., if, while, for, and case

Knowledge of functions, procedures, parameters, and return values

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 5 / 56

Motivation

PurposeMove processing into the DBMS from client programs (databaseapplications)

AdvantagesCode accessible to all applications

I Access from different programming languages

Very efficient for data intensive processingI Process large data set, small result returned

Enhance the security of database applicationsI Avoid SQL injection attackshttp://en.wikipedia.org/wiki/SQL_injection

Missing StandardUnfortunately, the major DBMS vendors each have their own SQL dialect

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 6 / 56

Motivation

PurposeMove processing into the DBMS from client programs (databaseapplications)

AdvantagesCode accessible to all applications

I Access from different programming languages

Very efficient for data intensive processingI Process large data set, small result returned

Enhance the security of database applicationsI Avoid SQL injection attackshttp://en.wikipedia.org/wiki/SQL_injection

Missing StandardUnfortunately, the major DBMS vendors each have their own SQL dialect

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 6 / 56

Overview

FunctionalitySQL extended with control structures

I Control structures like if and loop statements

Used forI Stored procedures (and functions)I Package (Oracle specific)I TriggersI Types a.k.a. classes (Oracle specific)

In very widely used in the industryI see http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html

In the SQL standard called SQL/PSMI PSM = Persistent Storage Model

FocusThe focus is here on stored procedures and packages!

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 7 / 56

Outline

1 Introduction

2 Stored ProceduresAn OverviewData TypesParameter ParsingCursors

3 PackagesCase Study: Table API

4 Summary

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 8 / 56

Motivation for Stored Procedures

The Big Four BenefitsAbstraction

I Increases readability

Implementation hidingI Can change internals without effecting clients

Modular programsI More manageable and easier to understand

LibraryI Reuse, reuse, and reuse!

NoteThis is not different from any other procedural programming language!

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 9 / 56

Outline

1 Introduction

2 Stored ProceduresAn OverviewData TypesParameter ParsingCursors

3 PackagesCase Study: Table API

4 Summary

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 10 / 56

A Procedure: Hello, World!

Example (The Start Program)create or rep lace procedure h e l l o w o r l d i sbegin

dbms output . p u t l i n e ( ’ Hel lo , World ! ’ ) ;end ;

NoteIt is a procedure, i.e., not a function

I Both a procedure and a function is called a stored procedure

It is a begin and end language, not curly brackets: { and }It uses a built-in library dbms output.put line

I The package dbms output has the procedure put lineI Uses the dot notation for invoking functions myPackage.myProcedure

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 11 / 56

A Function: Calculating Your BMIExample (A BMI Function)create or rep lace f u n c t i o n bmi ( he igh t i n t , weight f l o a t )r e t u r n f l o a t i sbegin

i f he igh t <= 0.3 or he igh t > 3.0 thendbms output . p u t l i n e ( ’ he igh t must be i n [ 0 . 3 , 3 . 0 ] meters ’ ) ;

end i f ;i f weight <= 0 then

dbms output . p u t l i n e ( ’ weight must be p o s i t i v e ’ ) ;e l s i f weight > 500 then

dbms output . p u t l i n e ( ’No human ’ ’ s weight i s 500 kg ’ ) ;end i f ;r e t u r n weight / he igh t ∗∗2;

end ;

NoteIt takes two parameters height and weight

It is a function, i.e., has a return statement

It is strongly typed language, i.e., parameters and the return value

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 12 / 56

Executing Stored Procedures

Example (Execute on Oracle server)−− to enable output from the serverSQL>set se rverou tpu t on

−− execute the procedureSQL>execute h e l l o w o r l d ;

−− execute the f u n c t i o nSQL>exec bmi (1 .87 , 90 ) ;−− r e s u l t s i n an er ro r , value re turned by f u n c t i o n must be used !

−− Wrap the f u n c t i o n c a l lSQL>exec dbms output . p u t l i n e ( bmi (1 .87 , 9 0 ) ) ;

NoteOutput 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 December 2, 2011 13 / 56

Executing Stored Procedures

Example (Execute on Oracle server)−− to enable output from the serverSQL>set se rverou tpu t on

−− execute the procedureSQL>execute h e l l o w o r l d ;

−− execute the f u n c t i o nSQL>exec bmi (1 .87 , 90 ) ;−− r e s u l t s i n an er ro r , value re turned by f u n c t i o n must be used !

−− Wrap the f u n c t i o n c a l lSQL>exec dbms output . p u t l i n e ( bmi (1 .87 , 9 0 ) ) ;

NoteOutput 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 December 2, 2011 13 / 56

Executing Stored Procedures

Example (Execute on Oracle server)−− to enable output from the serverSQL>set se rverou tpu t on

−− execute the procedureSQL>execute h e l l o w o r l d ;

−− execute the f u n c t i o nSQL>exec bmi (1 .87 , 90 ) ;−− r e s u l t s i n an er ro r , value re turned by f u n c t i o n must be used !

−− Wrap the f u n c t i o n c a l lSQL>exec dbms output . p u t l i n e ( bmi (1 .87 , 9 0 ) ) ;

NoteOutput 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 December 2, 2011 13 / 56

Executing Stored Procedures

Example (Execute on Oracle server)−− to enable output from the serverSQL>set se rverou tpu t on

−− execute the procedureSQL>execute h e l l o w o r l d ;

−− execute the f u n c t i o nSQL>exec bmi (1 .87 , 90 ) ;−− r e s u l t s i n an er ro r , value re turned by f u n c t i o n must be used !

−− Wrap the f u n c t i o n c a l lSQL>exec dbms output . p u t l i n e ( bmi (1 .87 , 9 0 ) ) ;

NoteOutput 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 December 2, 2011 13 / 56

Executing Stored Procedures

Example (Execute on Oracle server)−− to enable output from the serverSQL>set se rverou tpu t on

−− execute the procedureSQL>execute h e l l o w o r l d ;

−− execute the f u n c t i o nSQL>exec bmi (1 .87 , 90 ) ;−− r e s u l t s i n an er ro r , value re turned by f u n c t i o n must be used !

−− Wrap the f u n c t i o n c a l lSQL>exec dbms output . p u t l i n e ( bmi (1 .87 , 9 0 ) ) ;

NoteOutput 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 December 2, 2011 13 / 56

Using SQL in Stored Procedures

Example (Use the Data Stored)create or rep lace 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 ta . dsci n t o v s t a t u sfrom student stu , s ta tus s tawhere s tu . s t a t i d = sta . s t a t i dand stu . s id = s t u d e n t i d ;r e t u r n v s t a t u s ;

end ;

NoteThe 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

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 14 / 56

Calling Other Procedures

Example (Callee)create or rep lace procedure p ( s t varchar2 ) asbegin

dbms output . p u t l i n e ( s t ) ;end ;

Example (Caller)create or rep lace procedure c a l l p i sbegin

p ( ’ He l lo ’ ) ; p ( ’ World ! ’ ) ;end ;

NoteCan 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 December 2, 2011 15 / 56

Calling Other Procedures

Example (Callee)create or rep lace procedure p ( s t varchar2 ) asbegin

dbms output . p u t l i n e ( s t ) ;end ;

Example (Caller)create or rep lace procedure c a l l p i sbegin

p ( ’ He l lo ’ ) ; p ( ’ World ! ’ ) ;end ;

NoteCan 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 December 2, 2011 15 / 56

Calling Other Procedures

Example (Callee)create or rep lace procedure p ( s t varchar2 ) asbegin

dbms output . p u t l i n e ( s t ) ;end ;

Example (Caller)create or rep lace procedure c a l l p i sbegin

p ( ’ He l lo ’ ) ; p ( ’ World ! ’ ) ;end ;

NoteCan 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 December 2, 2011 15 / 56

Control Structures: A Crash Course I

Example (The If Statement)create or rep lace procedure pb ( va l boolean ) i sbegin

i f va l = t rue thendbms output . p u t l i n e ( ’ t r ue ’ ) ;

e l s i f va l = f a l s e thendbms output . p u t l i n e ( ’ f a l s e ’ ) ;

e lsedbms output . p u t l i n e ( ’ n u l l ’ ) ;

end i f ;end ;

NoteIs this stupid?

Recall three-valued logic the root of all evil!

We will use the procedure pb in the code that follows!

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 16 / 56

Control Structures: A Crash Course II

Example (The While Statement)create or rep lace procedure count 10 i s

i i n t := 1 ;begin

wh i le i < 10 loopdbms output . p u t l i n e ( i ) ;i := i + 1 ;

end loop ;

NoteWhat 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

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 17 / 56

Surprises: In General

SurprisesThe code is stored in the DBMS!

{ has been replaced by begin and } by end

SQL and programming logic blends very nicely!I A strong-point of PL/SQL

Procedures are different from functions

The assignment operator is := and not =

The comparison operator is = and not ==

Control structures are quite different from the C world

Three-valued logic will time and again surprise you!Server output is not enabled by default

I Which is a big surprise

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 18 / 56

Outline

1 Introduction

2 Stored ProceduresAn OverviewData TypesParameter ParsingCursors

3 PackagesCase Study: Table API

4 Summary

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 19 / 56

An ExampleExample (Various Data Types)create or rep lace procedure use bas ic types i s

v s t r varchar2 (30) := ’A s t r i n g ’ ;v i n t i n t := 2∗∗65;c p i constant f l o a t := 3.14159265358979323846264338327950288419;v f l o a t f l o a t := v i n t ∗ c p i ;

beginp ( v s t r ) ; p ( v i n t ) ; p ( v f l o a t ) ;

end ;

OutputA string36893488147419103232115904311329233965478,149216911761758199

NoteForget 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 definedKristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 20 / 56

Overview: Scalar Data TypesScalar Data Types

Description Type Examples

Integerssmallint -100, 0, 100int/integer -1000, 0, 1000positive 0, 1, 2, 3

Floatsnumber 10.3dec/decimal 123.456, 3.4real 123456.7890

Stringsvarchar2 Hello, Theta-Joinnvarchar2 Tøger, Dæmonchar World, Noise

Boolean Boolean True, FalseDate/time date 2007-09-09

timestamp 2009-09-09 12:34:56

NoteNot all of these data types are available from within SQL!

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 21 / 56

Quiz: The Decimal Data Type

Example (Rouding)create or rep lace procedure us ing dec imal 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 ;

QuestionsWill this compile, note that it is decimal(4,2)?

What will be printed (if it compiles)?

Are you surprised?

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 22 / 56

Overview: Other Data Types

Special Data Types

Description Type

CompositeRecordVarrayTable

Large ObjectsBLOBCLOBBFILE

Reference TypesREFREF CURSOR

NoteWe will only use records in this lecture.

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 23 / 56

Anchored Data Types: Type

Example (Anchor for a Column)create or rep lace f u n c t i o n ge t s ta tus anchored (

s t u d e n t i d s tudent . s id%type )r e t u r n s ta tus . dsc%type i s

v s t a t u s s ta tus . dsc%type ;begin

s e l e c t s ta . dsci n t o v s t a t u sfrom student stu , s ta tus s tawhere s tu . s t a t i d = sta . s t a t i dand stu . s id = s t u d e n t i d ;r e t u r n v s t a t u s ;

end ;

NoteThe anchored type using the %type

Very convenient of maintenance reasons (avoid “hard-wiring” types)I Widely used, you are encouraged to use it!

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 24 / 56

Anchored Data Types: Rowtype

Example (Anchor for a Table)create or rep lace procedure get course rowtype (

course id course . c id%type )i s

v row course%rowtype ;v tmp varchar2 ( 5 0 0 ) ;

begins e l e c t ∗i n t o v rowfrom course cwhere c . c id = course id ;v tmp := v row . cname | | ’ : ’ | | v row . dsc ;p ( v tmp ) ;

end ;

NoteThe anchored type using the rowtype

I Creates a record

The dot notation for access elements of the record

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 25 / 56

Surprises: Data Type

NoteStrings are a basic type, not an object like in Java or C#

I A maximum size must be specified

The sizes of the basic data type are very different from C and JavaDate and time are basic data types!

I This is very handy

The anchored types is something new compared to C and JavaBooleans are not a basic data type in SQL but in PL/SQL

I This sometimes leads to very annoying problems

Support for composite data type is not very good in PL/SQLcompared to C and JavaLOB objects are plain stupid

I But sometimes necessary

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 26 / 56

Outline

1 Introduction

2 Stored ProceduresAn OverviewData TypesParameter ParsingCursors

3 PackagesCase Study: Table API

4 Summary

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 27 / 56

OverviewExamplecreate or rep lace procedure p i n ( va l i n i n t ) i s

v tmp i n t ;begin

v tmp := va l + 5 ;−−va l := va l + 5 ; /∗ i l l e g a l va l i s read−only ∗ /

end ;

Examplecreate or rep lace procedure p i n o u t ( va l i n out i n t ) i sbegin

va l := va l + 5 ;end ;

Examplecreate or rep lace procedure c a l l p s i s

v i n i n t := 10;v i n o u t i n t := 10;

beginp i n ( v i n ) ; p ( v i n ) ;p i n o u t ( v i n o u t ) ; p ( v i n o u t ) ;

end ;

When execute call ps prints 10 and 15, why?

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 28 / 56

QuizExamplecreate or rep lace procedure p i n o u t ( va l i n out i n t ) i sbegin

va l := va l + 5 ;end ;

Examplecreate or rep lace procedure c a l l p s i s

v i n i n t := 10;v i n o u t i n t := 10;

beginp i n ( v i n ) ; p ( v i n ) ;p i n o u t ( v i n o u t ) ; p ( v i n o u t ) ;

end ;

QuestionsWhat are the formal parameter(s)?

What are the actual parameter(s)?

Is it call-by-value or call-by-reference?

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 29 / 56

Out Parameters

Examplecreate or rep lace procedure ge t x y coo r (

c oo r i d i n i n t , x coor out i n t , y coor out i n t )i sbegin

x coor := round ( c oo r i d / 4 . 2 ) ; −− s tup id c a l c u l a t i o n sy coor := round ( c oo r i d / 7 . 5 ) ;

end ;

Notein 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

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 30 / 56

Parameter Mode

Mode

Mode Description

in Formal parameter is read-onlyout Formal parameter is write-only

in out Formal parameter is read-write

Notein 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

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 31 / 56

What is Wrong Here?

create procedure proc 1 ( i i n t )i sbegin−− sn ip compl icated s t u f fr e t u r n i ;

end ;

create f u n c t i o n func 1 ( i i n t )r e t u r n i n t i sbegin−− sn ip compl icated s t u f fr e t u r n ’ h e l l o ’ ;

end ;A B

create f u n c t i o n func 2 ( i i n t )r e t u r n i n t i sbegin−− sn ip compl icated s t u f fr e t u r n i ∗2;p ( ’ h e l l o wor ld ’ ) ;

end ;

create f u n c t i o n func 3 ( i i n t )r e t u r n i n t i sbegin−− sn ip compl icated s t u f fp ( ’ h e l l o wor ld ’ ) ;

end ;

C D

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 32 / 56

Avoid This

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 33 / 56

Additional Comments on Parameters

Items to NoticeA default value can be provided for each parameter

Stored procedures cannot be overloaded on the parameter signature

Stored procedures can be called by position or by name

Works like in most programming languages, however different syntax!

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 34 / 56

Outline

1 Introduction

2 Stored ProceduresAn OverviewData TypesParameter ParsingCursors

3 PackagesCase Study: Table API

4 Summary

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 35 / 56

Overview

DefinitionA cursor is a mechanism that ensure a result set can be identified by adeclarative language such as SQL and processed by a procedurallanguage such as PL/SQL or C#

SolutionSolves the well-known impedance mismatch problem!

GeneralityKnowledge about cursors in PL/SQL is directly transferable to many otherprogramming languages.

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 36 / 56

Overview

DefinitionA cursor is a mechanism that ensure a result set can be identified by adeclarative language such as SQL and processed by a procedurallanguage such as PL/SQL or C#

SolutionSolves the well-known impedance mismatch problem!

GeneralityKnowledge about cursors in PL/SQL is directly transferable to many otherprogramming languages.

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 36 / 56

Overview

DefinitionA cursor is a mechanism that ensure a result set can be identified by adeclarative language such as SQL and processed by a procedurallanguage such as PL/SQL or C#

SolutionSolves the well-known impedance mismatch problem!

GeneralityKnowledge about cursors in PL/SQL is directly transferable to many otherprogramming languages.

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 36 / 56

The Unix ls commandExample (List Tables)create or rep lace procedure l s i s

cursor c t a b l e s i ss e l e c t ∗ from cat ;

v table name cat . table name%type ;v type cat . t a b l e t y p e%type ;

beginopen c t a b l e s ;loop

fe t ch c t a b l e s i n t o v table name , v type ;e x i t when c t a b l e s%notfound ;p ( v table name ) ;

end loop ;c lose c t a b l e s ;

end ;

NoteThe 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 December 2, 2011 37 / 56

Cursor Attributes

Attributes

Attribute Type Descriptionnotfound Boolean True if a record is fetched unsuccessfullyfound Boolean True if a record is fetched successfullyrowcount Integer The number of records fetched from the cursorisopen Boolean True if cursor is open

NoteThere are additional attributes for bulk operations.

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 38 / 56

Quiz: Using rowcount

Examplecreate or rep lace procedure l s c n t i s

cursor c t a b l e s i ss e l e c t table name from cat ;

v table name cat . table name%type ;begin

open c t a b l e s ;loop

fe t ch c t a b l e s i n t o v table name ;e x i t when c t a b l e s%notfound ;p ( c t a b l e s%rowcount | | ’ ’ | | v table name ) ;

end loop ;c lose c t a b l e s ;

end ;

QuestionWhat is printed?

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 39 / 56

Quiz: Using isopen?Examplecreate or rep lace procedure l s i sopen i s

cursor c t a b l e s i ss e l e c t table name from cat ;

v table name cat . table name%type ;v s t a t u s boolean := f a l s e ;

beginv 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

fe t ch c t a b l e s i n t o v table name ;e x i t when c t a b l e s%notfound ;

end loop ;v s t a t u s := c t a b l e s%isopen ; pb ( v s t a t u s ) ;c lose 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 ) ;

end ;

QuestionWhat is printed?

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 40 / 56

Outline

1 Introduction

2 Stored ProceduresAn OverviewData TypesParameter ParsingCursors

3 PackagesCase Study: Table API

4 Summary

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 41 / 56

Introduction

IdeaA class like conceptVery good for building libraries

I A way to cluster related stored procedures

Has a header and a body (think C-style languages)

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 42 / 56

Outline

1 Introduction

2 Stored ProceduresAn OverviewData TypesParameter ParsingCursors

3 PackagesCase Study: Table API

4 Summary

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 43 / 56

Introduction

GoalTo build a uniform way to address the data stored in table!

Methods

Name Description

exist(<primary key>) Return true if primary key existsto string(<primary key>) Return string representation of rowprint(<primary key>) Convenient way to display a row

NoteMany more methods can be envisioned

Think object-relational mapping (ORM) tools

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 44 / 56

Introduction

GoalTo build a uniform way to address the data stored in table!

Methods

Name Description

exist(<primary key>) Return true if primary key existsto string(<primary key>) Return string representation of rowprint(<primary key>) Convenient way to display a row

NoteMany more methods can be envisioned

Think object-relational mapping (ORM) tools

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 44 / 56

Header File: Course Table

Example (Header)create or rep lace package ccourse i s

f u n c t i o n e x i s t ( c id course . c id%type ) r e t u r n boolean ;f u n c t i o n t o s t r i n g ( c id course . c id%type ) r e t u r n s t r i n g ;procedure p r i n t ( c id course . c id%type ) ;

end ;

NoteThe 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#

QuizWhy is the method called exist and not exists?

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 45 / 56

Header File: Course Table

Example (Header)create or rep lace package ccourse i s

f u n c t i o n e x i s t ( c id course . c id%type ) r e t u r n boolean ;f u n c t i o n t o s t r i n g ( c id course . c id%type ) r e t u r n s t r i n g ;procedure p r i n t ( c id course . c id%type ) ;

end ;

NoteThe 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#

QuizWhy is the method called exist and not exists?

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 45 / 56

Body File: Private Method and CursorExample (Body)create or rep lace package body ccourse i s

−− p r i v a t e constantc e r r o r c i d n u l l constant i n t := −20001;−− a cursor used i n the implementat ioncursor c u r e x i s t ( cv c i d course . c id%type ) i s

s e l e c t c . c id , c . cname , c . semester , c . dscfrom course cwhere c . c id = cv c i d ;

−− a p r i v a t e methodprocedure c h e c k v a l i d c i d ( c id course . c id%type ) i sbegin

i f c id i s n u l l thenr a i s e a p p l i c a t i o n e r r o r ( c e r r o r c i d n u l l ,

’ Course ID i s n u l l ’ ) ;end i f ;

end ;

NoteThe method check valid cid is private

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 46 / 56

Body File: Private Method and CursorExample (Body)create or rep lace package body ccourse i s

−− p r i v a t e constantc e r r o r c i d n u l l constant i n t := −20001;−− a cursor used i n the implementat ioncursor c u r e x i s t ( cv c i d course . c id%type ) i s

s e l e c t c . c id , c . cname , c . semester , c . dscfrom course cwhere c . c id = cv c i d ;

−− a p r i v a t e methodprocedure c h e c k v a l i d c i d ( c id course . c id%type ) i sbegin

i f c id i s n u l l thenr a i s e a p p l i c a t i o n e r r o r ( c e r r o r c i d n u l l ,

’ Course ID i s n u l l ’ ) ;end i f ;

end ;

NoteThe method check valid cid is private

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 46 / 56

Body File: The Exist Method

Example (Method)f u n c t i o n e x i s t ( c id course . c id%type ) r e t u r n boolean i s

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 id ) ; −− p recond i t i onopen c u r e x i s t ( c id ) ;f e t ch c u r e x i s t i n t o r e c e x i s t ;c lose c u r e x i s t ;r e t u r n ( r e c e x i s t . c id i s not n u l l ) ;

end ;

NoteUses the private method check valid cid to check preconditions

Uses the private cursor cur exist

Returns true if a valid primary key is found

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 47 / 56

Body File: The to string Method

Example (Method)f u n c t i o n t o s t r i n g ( c id course . c id%type ) r e t u r n s t r i n g i s

v r v s t r i n g ( 5 1 2 ) ;r e c e x i s t c u r e x i s t%rowtype ;

beginc h e c k v a l i d c i d ( c id ) ; −− p recond i t i onopen c u r e x i s t ( c id ) ;f e t ch c u r e x i s t i n t o r e c e x i s t ;c lose 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 ;r e t u r n v r v ;

end ;

NoteUses the private method check valid cid to check preconditions

Uses the private cursor cur exist

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 48 / 56

Body File: The print Methods

Example (Method)procedure p r i n t ( c id course . c id%type ) i sbegin

c h e c k v a l i d c i d ( c id ) ; −− p recond i t i ondbms output . p u t l i n e ( t o s t r i n g ( c id ) ) ;

end ;

NoteUses the private method check valid cid to check preconditions

print calls to string

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 49 / 56

Exercising the Package

ExampleSQL>set se rverou tpu t on−− execute the procedureSQL>execute ccourse . p r i n t ( 4 ) ;

NoteSimilar to executing a stored procedure

Access member by the dot notation

ExampleSQL>execute ccourse . p r i n t ( n u l l ) ;

NoteResults in an error “ORA-20001: Course ID is null”

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 50 / 56

Exercising the Package

ExampleSQL>set se rverou tpu t on−− execute the procedureSQL>execute ccourse . p r i n t ( 4 ) ;

NoteSimilar to executing a stored procedure

Access member by the dot notation

ExampleSQL>execute ccourse . p r i n t ( n u l l ) ;

NoteResults in an error “ORA-20001: Course ID is null”

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 50 / 56

Exercising the Package

ExampleSQL>set se rverou tpu t on−− execute the procedureSQL>execute ccourse . p r i n t ( 4 ) ;

NoteSimilar to executing a stored procedure

Access member by the dot notation

ExampleSQL>execute ccourse . p r i n t ( n u l l ) ;

NoteResults in an error “ORA-20001: Course ID is null”

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 50 / 56

Summary: Packages

Main PointsCan have a public and a private part

I Has no protected access modifiers as in Java or C#

Is used to cluster related stored procedures

Cursors, constants, and variables can be shared between methods ina package

The foundation for building larger libraries in PL/SQL

There is a huge library of built-it packages on Oracle

Has very good exception handling facilities

Comparison to Object-Oriented LanguagesNo inheritance

Only static methods

No concept of an object

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 51 / 56

Outline

1 Introduction

2 Stored ProceduresAn OverviewData TypesParameter ParsingCursors

3 PackagesCase Study: Table API

4 Summary

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 52 / 56

Advantages

AdvantagesA complete programming language

I You are not missing stuff as you sometimes are in SQL

In wide-spread usage in the industryI Adds to your market value

Very good integration of programming logic and SQLImpedance mismatch is basically removed

I PL/SQL data types are super set of SQL data typesI Cursors enable the processing of sets (or bags)

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 53 / 56

Disadvantages

DisadvantagesProprietary programming languageThere is a very large number (>1000) of reserved words

I Can be hard to come up with a variable name that is not a reservedword!

Pascal-family language (C-family more well-known)I Which lead to a number of surprises

Object-oriented features are “clumsy”I This has not been covered in this lecture

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 54 / 56

Additional Information

Web Siteswww.oracle.com/technology/tech/pl_sql/index.html

PL/SQL’s home

www.psoug.org/library.html A very good and complete wiki withPL/SQL information

plsql-tutorial.com/ A crash course covering many PL/SQLfeatures

en.wikibooks.org/wiki/Oracle_Programming/SQL_Cheatsheet

A short overview of PL/SQL

www.java2s.com/Tutorial/Oracle/CatalogOracle.htm Manygood examples, too many commercials

Kristian Torp (Aalborg University) Introduction to PL/SQL December 2, 2011 55 / 56