Introduction to PL/SQL

Kristian Torp
Department of Computer Science Aalborg Univeristy

www.cs.aau.dk/ torp torp@cs.aau.dk

November 30, 2009

daisy.aau.dk
Kristian Torp (Aalborg University) Introduction to PL/SQL November 30, 2009 1 / 55

Outline

1

Introduction Stored Procedures An Overview Data Types Parameter Parsing Cursors Packages Case Study: Table API Summary

2

3

4

Kristian Torp (Aalborg University)

Introduction to PL/SQL

November 30, 2009

2 / 55

Learning Outcomes

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

Kristian Torp (Aalborg University)

Introduction to PL/SQL

November 30, 2009

4 / 55

Prerequisites
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

Procedural Programming Language
Knowledge 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

November 30, 2009

5 / 55

wikipedia. small result returned Enhance the security of database applications Avoid SQL injection attacks http://en. the major DBMS vendors each have their own SQL dialect Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.org/wiki/SQL_injection Missing Standard Unfortunately. 2009 6 / 55 .Motivation 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.

k. 2009 7 / 55 .a.php/content/paperinfo/ tpci/index.com/index.tiobe.html In the SQL standard called SQL/PSM PSM = Persistent Storage Model Focus The focus is here on stored procedures and packages! Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.Overview SQL extended with control structures Control structures like if and loop statements Used for Stored procedures (and functions) Package Triggers Types a. classes In very widely used in the industry see http://www.

reuse. 2009 9 / 55 .Motivation for Stored Procedures The Big Four Benefits Abstraction Increases readability Implementation hiding Can change internals without effecting clients Modular programs More manageable and easier to understand Library Reuse. and reuse! Note This is not different from any other procedural programming language! Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.

A Procedure: Hello. not curly brackets: { and } It uses a built-in library dbms output.. World ! ’ ) .put line The package dbms output has the procedure put line Uses the dot notation for invoking functions myPackage. end . 2009 11 / 55 . World! 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 . not a function It is a begin and end language. Note It is a procedure. i.e.myProcedure Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.

A Function: Calculating Your BMI c r e a t e o r r e p l a c e f u n c t i o n bmi ( h e i g h t i n t . 3 . i f w e i g h t <= 0 then dbms output . 3 .. i. 3 o r h e i g h t > 3 . 0 ] meters ’ ) . p u t l i n e ( ’ h e i g h t must be i n [ 0 . e l s i f w e i g h t > 500 then dbms output . end i f . i. p u t l i n e ( ’No human ’ ’ s w e i g h t i s 500 kg ’ ) . end . has a return statement It takes parameters height and weight It is strongly typed language.e. p u t l i n e ( ’ w e i g h t must be p o s i t i v e ’ ) . w e i g h t f l o a t ) return f l o a t is begin i f h e i g h t <= 0 . end i f . parameters and the return value Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. 0 then dbms output . r e t u r n weight / height ∗∗2.e.. Note It is a function. 2009 12 / 55 .

−− execute t h e f u n c t i o n SQL>exec bmi ( 1 . p u t l i n e ( bmi ( 1 . 8 7 .Executing Stored Procedures Log on to your Oracle server −− 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 . 8 7 . 9 0 ) . 2009 13 / 55 . −− 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 . 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 14 / 55 . end . sid = student id .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 ) . s t a t u s s t a where s t u . s t a t i d and stu . 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 Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. s t a t i d = s t a . begin s e l e c t s t a . return v status . dsc into v status from s t u d e n t stu .

p u t l i n e ( s t ) . end .Calling Other Procedures Callee c r e a t e o r r e p l a c e procedure p ( s t v a r c h a r 2 ) as begin dbms output .put line You are now officially a PL/SQL library builder!!! Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. p ( ’ World ! ’ ) . 2009 15 / 55 . end . Note Can call own and built-in stored procedures Will use the procedure p instead of dbms output. 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 ’ ) .

else dbms output . end i f . Note Is 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 November 30. e l s i f v a l = f a l s e then dbms output .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 . end . p u t l i n e ( ’ n u l l ’ ) . p u t l i n e ( ’ f a l s e ’ ) . p u t l i n e ( ’ t r u e ’ ) . 2009 16 / 55 .

very different from C PL/SQL does not have increment/decrement operators..g.g. end l o o p . p u t l i n e ( i ) .. e. i +=7 or j ∗=2 Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. e. Note What is printed 1 to 9 or 1 to 10? PL/SQL also has a for statement. i −− or ++j PL/SQL does not have compound assignments.Control Structures: A Crash Course II 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. i := i + 1. begin w h i l e i < 10 l o o p dbms output . 2009 17 / 55 .

2009 18 / 55 .Surprises: In General The code is stored in the DBMS! { has been replaced by begin and } by end SQL and programming logic blends very nicely! 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 Which is a big surprise Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.

14159265358979323846264338327950288419.An Example c r e a t e o r r e p l a c e procedure u s e b a s i c t y p e s i s v s t r v a r c h a r 2 ( 3 0 ) : = ’A s t r i n g ’ . 2009 20 / 55 . v f l o a t f l o a t := v i n t ∗ c p i . v i n t i n t : = 2 ∗∗ 65. begin p( v str ).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. p( v float ). c p i c o n s t a n t f l o a t : = 3. p( v int ). end . Output A string 36893488147419103232 115904311329233965478.

Overview: Scalar Data Types Description Integers Type smallint int/integer positive number dec/decimal real varchar2 nvarchar2 char Boolean date timestamp Examples -100.7890 Hello. 2009 21 / 55 . Theta-Join Tøger. 0. 3. 1. False 2007-09-09 2009-09-09 12:34:56 Floats Strings Boolean Date/time Note Not all of these data types are available from within SQL! Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.4 123456. Dæmon World. 3 10. 100 -1000. Noise True. 1000 0.3 123. 2.456. 0.

Questions Will this compile.344. p u t l i n e ( v dec ) . := 12. p u t l i n e ( v dec ) . := 12. output . 2009 22 / 55 . r e p l a c e procedure u s i n g d e c i m a l i s decimal ( 4 . note that it is decimal(4. := 12.Quiz: The Decimal Data Type create or v dec begin v dec dbms v dec dbms v dec dbms end .2)? What will be printed (if it compiles)? Are you surprised? Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.34.347. output . output . p u t l i n e ( v dec ) . 2 ) .

Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. 2009 23 / 55 .Overview: Other Data Types Description Composite Type Record Varray Table BLOB CLOB BFILE REF REF CURSOR Large Objects Reference Types Note We will only use records in this lecture.

s t a t i d = s t a . you are encouraged to use it! Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. 2009 24 / 55 . dsc into v status from s t u d e n t stu . begin s e l e c t s t a . dsc%t y p e . return v status . end .Anchored Data Types: Type create or replace f u n c t i o n get status anchored ( s t u d e n t i d s t u d e n t . s t a t u s s t a where s t u . Note The anchored type using the %type Very convenient of maintenance reasons (avoid “hard-wiring” types) Widely used. dsc%t y p e i s v s t a t u s s t a t u s . sid = student id . s t a t i d and stu . s i d%t y p e ) r e t u r n s t a t u s .

begin select ∗ into v row from course c where c . Note The anchored type using the rowtype Creates a record The dot notation for access elements of the record String concatenation is || Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. c i d = c o u r s e i d .Anchored Data Types: Rowtype c r e a t e o r r e p l a c e procedure g e t c o u r s e r o w t y p e ( c o u r s e i d course . cname | | ’ : ’ | | v row . p ( v tmp ) . v tmp v a r c h a r 2 ( 5 0 0 ) . dsc . end . c i d%t y p e ) is v row course%rowtype . 2009 25 / 55 . v tmp : = v row .

2009 26 / 55 .Surprises: Data Type Strings are a basic type. not an object like in Java or C# A maximum size must be specified The sizes of the basic data type are very different from C and Java Date and time are basic data types! This is very handy The anchored types is something new compared to C and Java Booleans are not a basic data type in SQL but in PL/SQL This sometimes leads to very annoying problems Support for composite data type is not very good in PL/SQL compared to C and Java LOB objects are plain stupid But sometimes necessary Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.

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. why? Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. When execute call ps prints 10 and 15. end . p in out ( v in out ) . 2009 28 / 55 .Overview create or v tmp begin v tmp −− v a l end . / ∗ i l l e g a l v a l i s read − o n l y ∗ / 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 . : = v a l + 5 . := val + 5. p( v in ) . begin p in ( v in ) . r e p l a c e procedure p i n ( v a l i n i n t ) i s int . v i n o u t i n t := 10. p( v in out ) .

p( v in ) .Quiz 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. v i n o u t i n t := 10. 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. end . p( v in out ) . Questions What 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 November 30. begin p in ( v in ) . end . p in out ( v in out ) . 2009 29 / 55 .

2 ) . 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 Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. end . x coor out i n t .Out Parameters 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 . 5 ) . 2009 30 / 55 . y coor out i n t ) is begin x c o o r : = round ( c o o r i d / 4 . −− 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 .

2009 31 / 55 .Parameter Mode Mode in out in out Description Formal parameter is read-only Formal parameter is write-only 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 Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.

C D Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. end . A create function func 2 ( i i n t ) return i n t is begin −− s n i p c o m p l i c a t e d s t u f f return i ∗2. B create function func 3 ( i i n t ) return i n t is begin −− s n i p c o m p l i c a t e d s t u f f p ( ’ h e l l o world ’ ) . create function func 1 ( i i n t ) return i n t is begin −− s n i p c o m p l i c a t e d s t u f f return ’ hello ’ . end . 2009 32 / 55 . p ( ’ h e l l o world ’ ) . end .What is Wrong Here? c r e a t e procedure p r o c 1 ( i i n t ) is begin −− s n i p c o m p l i c a t e d s t u f f return i . end .

2009 33 / 55 .Additional Comments on Parameters A 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 November 30.

Overview 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. Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. 2009 35 / 55 .

p ( v t a b le n a m e ) . loop f e t c h c t a b l e s i n t o v table name . t a b l e t y p e%t y p e .The Unix ls command c r e a t e o r r e p l a c e procedure l s i s cursor c tables i s s e l e c t ∗ from c a t . and closed Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. fetched. e x i t when c t a b l e s%n o t f ou n d . Note The view tab is a table that contains all table names The cursor is declared. end l o o p . v type c a t . v t a b le n a m e c a t . 2009 36 / 55 . close c tables . end . v t y p e . opened. table name%t y p e . begin open c t a b l e s .

2009 37 / 55 . Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.Cursor Attributes Attribute notfound found rowcount isopen Type Boolean Boolean Integer Boolean Description True if a record is fetched unsuccessfully True if a record is fetched successfully The number of records fetched from the cursor True if cursor is open Note There are additional attributes for bulk operations.

Quiz: Using rowcount 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 . end . 2009 38 / 55 . e x i t when c t a b l e s%n o t f ou n d . What is printed? Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. table name%t y p e . v t a b le n a m e c a t . close c tables . begin open c t a b l e s . p ( c t a b l e s%rowcount | | ’ ’ | | v t a b le n a m e ) . end l o o p . 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 .

begin v s t a t u s : = c t a b l e s%isopen . v s t a t u s : = c t a b l e s%isopen . What is printed? Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. ).Quiz: Using isopen? 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 s t a t u s boolean : = f a l s e . ). e x i t when c t a b l e s%n o t f ou n d . v t a b le n a m e c a t . 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 . 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 close c tables . end l o o p . 2009 39 / 55 . ). pb ( v s t a t u s end . v s t a t u s : = c t a b l e s%isopen . table name%t y p e .

2009 41 / 55 .Introduction A class like concept Very good for building libraries 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 November 30.

Introduction Goal To build a uniform way to address the data stored in table! Name Description Return true if primary key exists Return string representation of row Convenient way to display a row exist(<primary key>) to string(<primary key>) print(<primary key>) Note Many more methods can be envisioned Think object-relational mapping (ORM) tools Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. 2009 43 / 55 .

c i d%t y p e ) r e t u r n boolean . end .Header File: Course Table 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 . f u n c t i o n t o s t r i n g ( c i d course . 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? Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. c i d%t y p e ) . c i d%t y p e ) r e t u r n s t r i n g . 2009 44 / 55 . procedure p r i n t ( c i d course .

c i d%t y p e ) i s s e l e c t c . 2009 45 / 55 . c .Body File: Private Method and Cursor c r e a t e o r r e p l a c e package body ccourse i s −− p r i v a t e c o n s t a n t c e r r o r c i d n u l l c o n s t a n t i n t : = − 20001. semester . dsc from course c where c . ’ Course ID i s n u l l ’ ) . end i f . c i d . end . c . cname . −− a c u r s o r used i n t h e i m p l e m e n t a t i o n c u r s o r c u r e x i s t ( c v c i d course . Note The cursor cur exist is declared outside the methods The method check valid cid is private Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. c i d = c v c i d . −− a p r i v a t e method procedure c h e c k v a l i d c i d ( c i d course . c i d%t y p e ) i s begin i f c i d i s n u l l then raise application error ( c error cid null . c .

Body File: The Exist Method f u n c t i o n e x i s t ( c i d course . r e t u r n ( r e c e x i s t . fetch cur exist into rec exist . c i d%t y p e ) 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 . −− p r e c o n d i t i o n open c u r e x i s t ( c i d ) . begin c h e c k v a l i d c i d ( c i d ) . cid i s not n u l l ) . 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 Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. 2009 46 / 55 . end . close c u r e x i s t .

−− p r e c o n d i t i o n open c u r e x i s t ( c i d ) . c i d%t y p e ) i s begin c h e c k v a l i d c i d ( c i d ) . Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. 2009 47 / 55 . end . 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). procedure p r i n t ( c i d course . end . return v rv . end . close c u r e x i s t . begin c h e c k v a l i d c i d ( c i d ) . r e c e x i s t c u r e x i s t%rowtype .Body File: The to string and print Methods I f u n c t i o n t o s t r i n g ( c i d course . fetch cur exist into rec exist . dsc . cname | | ’ ’ | | ’ course desc : ’ | | r e c e x i s t . v r v : = ’ course name : ’ | | r e c e x i s t . p u t l i n e ( t o s t r i n g ( c i d ) ) . −− p r e c o n d i t i o n dbms output .

2009 48 / 55 .Body File: The to string and print Methods II Note Uses the private method check valid cid to check preconditions Uses the private cursor cur exist print calls to string Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.

p r i n t ( n u l l ) . 2009 49 / 55 . p r i n t ( 4 ) . Note Results in an error “ORA-20001: Course ID is null” Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. Note Similar to executing a stored procedure Access member by the dot notation SQL> execute ccourse .Exercising the Package 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 .

and variables can be shared between methods in a 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 Languages No inheritance Only static methods No concept of an object Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.Summary: Packages Can have a public and a private part Has no protected access modifiers as in Java or C# Is used to cluster related stored procedures Cursors. 2009 50 / 55 . constants.

2009 52 / 55 .Advantages A complete programming language You are not missing stuff as you sometimes are in SQL In wide-spread usage in the industry Adds to your market value Very good integration of programming logic and SQL Impedance mismatch is basically removed PL/SQL data types are super set of SQL data types Cursors enable the processing of sets (or bags) Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.

Disadvantages Proprietary programming language There is a very large number (>1000) of reserved words Can be hard to come up with a variable name that is not a reserved word! Pascal-family language (C-family more well-known) Which lead to a number of surprises Object-oriented features are “clumsy” This has not been covered in this lecture Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. 2009 53 / 55 .

2009 54 / 55 . and pipelined options External stored procedures Invoker rights vs.Some Topics Not Covered Limited about exception handling Parallel. definer rights Calling stored procedures from SQL Pragmas to stored procedures There are a Lot of Details Go and study the manuals and books! Kristian Torp (Aalborg University) Introduction to PL/SQL November 30. deterministic.

2009 55 / 55 .wikibooks.Additional Information www. too many commercials Kristian Torp (Aalborg University) Introduction to PL/SQL November 30.htm Many good examples.com/ A crash course covering many PL/SQL features en.org/wiki/Oracle_Programming/SQL_Cheatsheet A short overview of PL/SQL www.com/Tutorial/Oracle/CatalogOracle.org/library.html A very good and complete wiki with PL/SQL information plsql-tutorial.psoug.java2s.com/technology/tech/pl_sql/index.oracle.html PL/SQL’s home www.

Sign up to vote on this title
UsefulNot useful