You are on page 1of 186

PL/SQL Tutorial

Table of Contents
PL/SQL Tutorial........................................................................ iii Audience .................................................................................. iii Prerequisites ............................................................................ iii Copyright & Disclaimer Notice.................................................. iii PL/SQL !er!ie"..................................................................... #
$eatures o% PL/SQL ................................................................................... # Ad!antages o% PL/SQL .............................................................................. &

'n!ironment (

.............................................................................

Step # ........................................................................................................ ( Step & ........................................................................................................ ) Step ( ........................................................................................................ ) Step ) ........................................................................................................ * Step * ........................................................................................................ + Step + ........................................................................................................ + Step , ........................................................................................................ , Step - ........................................................................................................ , Step . ........................................................................................................ Step #/ ...................................................................................................... . Step ## .................................................................................................... #/ $inal Step................................................................................................. ## Te0t 'ditor ............................................................................................... #&

1asic Synta0 .......................................................................... #(


The 23ello 4orld2 '0ample5...................................................................... #( The PL/SQL 6denti%iers ............................................................................ #) The PL/SQL Delimiters ............................................................................ #) The PL/SQL Comments........................................................................... #* PL/SQL Program 7nits ............................................................................ #*

Data Types............................................................................. #,
PL/SQL Scalar Data Types and Su8types ............................................... #, PL/SQL Numeric Data Types and Su8types ............................................ #-

PL/SQL Character Data Types and Su8types ......................................... #. PL/SQL 1oolean Data Types................................................................... #.
iii

PL/SQL Datetime and 6nter!al Types ...................................................... #. PL/SQL Large 89ect :L 1; Data Types ................................................. &/ PL/SQL 7ser<De%ined Su8types .............................................................. &# N7LLs in PL/SQL .................................................................................... &#

=aria8les ................................................................................ &&


=aria8le Declaration in PL/SQL ............................................................... && 6nitiali>ing =aria8les in PL/SQL ................................................................ &( =aria8le Scope in PL/SQL ....................................................................... &( Assigning SQL Query ?esults to PL/SQL =aria8les ................................ &)

Constants ............................................................................... &+


Declaring a Constant ............................................................................... &+ The PL/SQL Literals ................................................................................ &,

perators ............................................................................... &Arithmetic perators ................................................................................ &'0ample5.................................................................................................. &. ?elational perators ................................................................................ &. '0ample5.................................................................................................. &. Comparison perators ............................................................................ (/ L6@' perator5......................................................................................... (# 1'T4''N perator5 ............................................................................... (# 6N and 6S N7LL perators5...................................................................... (& Logical perators .................................................................................... (( '0ample5.................................................................................................. (( PL/SQL perator Precedence ................................................................. (( '0ample5.................................................................................................. ()

Conditions .............................................................................. (*
Synta05..................................................................................................... (+ $lo" Diagram5.......................................................................................... (+ '0ample #5............................................................................................... (, '0ample &5............................................................................................... (, Synta05..................................................................................................... ($lo" Diagram5.......................................................................................... ('0ample5.................................................................................................. (. Synta05..................................................................................................... )/ '0ample5.................................................................................................. )/ Synta05..................................................................................................... )/ $lo" Diagram5.......................................................................................... )# '0ample5.................................................................................................. )# Synta05..................................................................................................... )&
iii

$lo" Diagram5.......................................................................................... )& '0ample5.................................................................................................. )& Synta05..................................................................................................... )( '0ample5.................................................................................................. )(

Loops ..................................................................................... ))
Synta05..................................................................................................... )* '0ample5.................................................................................................. )* Synta05..................................................................................................... )+ '0ample5.................................................................................................. )+ Synta05..................................................................................................... ), '0ample5.................................................................................................. ), ?e!erse $ ? L P Statement............................................................... )'0ample5.................................................................................................. ). La8eling a PL/SQL Loop.......................................................................... */ The Loop Control Statements .................................................................. *# Synta05..................................................................................................... *# $lo" Diagram5.......................................................................................... *# '0ample5.................................................................................................. *& The 'A6T 43'N Statement .................................................................... *& Synta05..................................................................................................... *& '0ample5.................................................................................................. *& Synta05..................................................................................................... *( $lo" Diagram5.......................................................................................... *( '0ample5.................................................................................................. *) Synta05..................................................................................................... *) $lo" Diagram5.......................................................................................... ** '0ample5.................................................................................................. ** ?estrictions "ith B T Statement .......................................................... *+

Strings.................................................................................... *,
Declaring String =aria8les ....................................................................... *, PL/SQL String $unctions and perators ................................................. *'0ample #................................................................................................ +/ '0ample &................................................................................................ +/

Arrays..................................................................................... +&
Creating a =array Type............................................................................ +& '0ample #................................................................................................ +(

Procedures............................................................................. +*
Parts o% a PL/SQL Su8program ............................................................... +* Creating a Procedure............................................................................... ++
iii

'0ample5.................................................................................................. ++ '0ecuting a Standalone Procedure ......................................................... +, Deleting a Standalone Procedure ............................................................ +, Parameter Codes in PL/SQL Su8programs ............................................ +, 6N & 7T Code '0ample # ..................................................................... +6N & 7T Code '0ample & ..................................................................... +Cethods %or Passing Parameters............................................................. +.
P S6T6 NAL N TAT6 N....................................................................... +. NAC'D N TAT6 N ............................................................................... +. C6A'D N TAT6 N ................................................................................. +.

$unctions ............................................................................... ,/
'0ample5.................................................................................................. ,# Calling a $unction .................................................................................... ,# '0ample5.................................................................................................. ,& PL/SQL ?ecursi!e $unctions................................................................... ,&

Cursors .................................................................................. ,)
6mplicit Cursors ........................................................................................ ,) '0ample5.................................................................................................. ,* '0plicit Cursors ........................................................................................ ,+ Declaring the Cursor ................................................................................ ,+ pening the Cursor ................................................................................. ,+ $etching the Cursor ................................................................................. ,+ Closing the Cursor ................................................................................... ,, '0ample5.................................................................................................. ,,

?ecords.................................................................................. ,Ta8le<1ased ?ecords .............................................................................. ,Cursor<1ased ?ecords ............................................................................ ,. 7ser<De%ined ?ecords ............................................................................. ,. De%ining a ?ecord .................................................................................... -/ Accessing $ields ...................................................................................... -/ ?ecords as Su8program Parameters ...................................................... -#

'0ceptions ............................................................................. -(
Synta0 %or '0ception 3andling................................................................. -( '0ample................................................................................................... -( ?aising '0ceptions .................................................................................. -) 7ser<de%ined '0ceptions.......................................................................... -) '0ample5.................................................................................................. -* Pre<de%ined '0ceptions............................................................................ -*

Triggers.................................................................................. -iii

1ene%its o% Triggers.................................................................................. -Creating Triggers ..................................................................................... -. '0ample5.................................................................................................. -. Triggering a Trigger ................................................................................. ./

PacDages ............................................................................... .&


PacDage Speci%ication ............................................................................. .& PacDage 1ody.......................................................................................... .( 7sing the PacDage 'lements................................................................... .( '0ample5.................................................................................................. .(
T3' PAC@AB' SP'C6$6CAT6 N5......................................................... .) C?'AT6NB T3' PAC@AB' 1 DE5 ...................................................... .) 7S6NB T3' PAC@AB'5 ......................................................................... .*

Collections ............................................................................. .+
6nde0<1y Ta8le......................................................................................... ., '0ample5.................................................................................................. ., '0ample5.................................................................................................. .Nested Ta8les.......................................................................................... .'0ample5.................................................................................................. .. '0ample5.................................................................................................. .. Collection Cethods ................................................................................ #// Collection '0ceptions ............................................................................ #/#

Transactions ........................................................................ #/(


Starting an 'nding a Transaction........................................................... #/( Committing a Transaction ...................................................................... #/) ?olling 1acD Transactions ..................................................................... #/) Sa!epoints ............................................................................................. #/) Automatic Transaction Control............................................................... #/*

Date & Time ......................................................................... #/+


$ield =alues %or Datetime and 6nter!al Data Types................................ #/+ The Datetime Data Types and $unctions .............................................. #/, '0amples5 .............................................................................................. #/. The 6nter!al Data Types and $unctions ................................................. ##/

D1CS 89ect

utput ....................................................................... ### riented .................................................................... ##(

D1CSF 7TP7T Su8programs ............................................................. ### '0ample5................................................................................................ ##& 6nstantiating an 89ect ........................................................................... ##) Cem8er Cethods ................................................................................... ##) 7sing Cap method................................................................................. ##*
iii

7sing rder method .............................................................................. ##+ 6nheritance %or PL/SQL 89ects5 ............................................................ ##, A8stract 89ects in PL/SQL ................................................................... ##.

iii

CHAPTER

PL/SQL Overview
This chapter describes the basic definition and concepts PL/SQL:

he PL/SQL programming language "as de!eloped 8y

racle Corporation in the late

#.-/s as procedural e0tension language %or SQL and the $ollo"ing are nota8le %acts a8out PL/SQL5

racle relational data8ase.

PL/SQL is a completely porta8leG high<per%ormance transaction<processing language. PL/SQL pro!ides a 8uilt<in interpreted and S independent programming en!ironment.

PL/SQL can also directly 8e called %rom the command<line SQLHPlus inter%ace. Direct call can also 8e made %rom e0ternal programming language calls to data8ase. PL/SQL2s general synta0 is 8ased on that o% ADA and Pascal programming language. Apart %rom racleG PL/SQL is a!aila8le in TimesTen in<memory data8ase and 61C D1&.

Features of PL/SQL
PL/SQL has the %ollo"ing %eatures5

PL/SQL is tightly integrated "ith SQL. 6t o%%ers e0tensi!e error checDing. 6t o%%ers numerous data types. 6t o%%ers a !ariety o% programming structures. 6t supports structured programming through %unctions and procedures. 6t supports o89ect oriented programming.

TUTORIALSPOINT Simply Easy Learning

Page 1

6t supports de!eloping "e8 applications and ser!er pages.

Advantages PL/SQL
PL/SQL has the %ollo"ing ad!antages5

of

SQL is the standard data8ase language and PL/SQL is strongly integrated "ith SQL. PL/SQL
supports 8oth static and dynamic SQL. Static SQL supports DCL operations and transaction control %rom PL/SQL 8locD. Dynamic SQL is SQL allo"s em8edding DDL statements in PL/SQL 8locDs.

PL/SQL allo"s sending an entire 8locD o% statements to the data8ase at one time.
This reduces net"orD tra%%ic and pro!ides high per%ormance %or the applications.

PL/SQL gi!e high producti!ity to programmers as it can queryG trans%ormG and update data
in a data8ase.

PL/SQL sa!es time on design and de8ugging 8y strong %eaturesG such as e0ception
handlingG encapsulationG data hidingG and o89ect<oriented data types.

Applications "ritten in PL/SQL are %ully porta8le. PL/SQL pro!ides high security le!el. PL/SQL pro!ides access to prede%ined SQL pacDages. PL/SQL pro!ides support %or 89ect< riented Programming.
PL/SQL pro!ides support %or De!eloping 4e8 Applications and Ser!er Pages.

TUTORIALSPOINT Simply Easy Learning

Page 2

CHAPTER

Environme nt
This chapter describes the environment setup for starting with PL/SQl:

L/SQL is not a stand<alone programming languageI it is a tool "ithin the

racle

programming en!ironment. SQLH Plus is an interacti!e tool that allo"s you to type SQL and PL/SQL statements at the command prompt. These commands are then sent to the data8ase %or processing. nce the statements are processedG the results are sent 8acD and displayed on screen. To run PL/SQL programs you should ha!e racle ?1DCS Ser!er installed in your machine "hich "ill taDe care o% e0ecuting SQL commands. Cost recent !ersion o% racle ?D1CS is ##g. Eou can do"nload a trial !ersion o% racle ##g %rom the %ollo"ing linD5 Do"nload racle ##g '0press 'dition

Eou "ill ha!e to do"nload either (&8it or +) 8it !ersion o% the installation as per your operating system. 7sually there are t"o %ilesG as 6 ha!e do"nloaded %or +) 8it 4indo"s,. Eou "ill also use similar steps on your operating systemG does not matter i% it is Linu0 or Solaris.

win64_11gR2_database_1of2.zip win64_11gR2_database_2of2.zip them in a

A%ter don"loading a8o!e t"o %ilesG you "ill need to un>ip single directory database and under that you "ill %ind %ollo"ing su8<directories5

Step 1
No" let2s launch racle Data8ase 6nstaller using setup %ile. $ollo"ing is the %irst screen. Eou can pro!ide your email 6D and unchecDG checD 8o0 and clicD Next 8utton5

TUTORIALSPOINT Simply Easy Learning

Page 3

Step 2
Eou "ill ha!e %ollo"ing screenG 9ust unchecD the checD 8o0 and clicD continue 8utton to proceed.

Step 3
Just select %irst option Create and Configure Database using radio 8utton and clicD Next 8utton to proceed5

TUTORIALSPOINT Simply Easy Learning

Page 4

Step 4
6 assume you are installing racle 9ust %or learning purpose and you "ill install it on your PC or Laptop. So select Desktop Class option and clicD Next 8utton to proceed5

TUTORIALSPOINT Simply Easy Learning

Page 5

Step
Pro!ide a location "here you "ill install racle Ser!er. Just modi%y racle !ase and rest o% the locations "ill set automatically. Second you "ill ha!e to pro!ide a pass"ord "hich "ill 8e used 8y system D1A. nce you pro!ide required in%ormationG clicD Next 8utton to proceed5

Step !
Just clicD Next 8utton to proceed5

TUTORIALSPOINT Simply Easy Learning

Page 6

Step "
No" clicD "inis# 8utton to proceedG this "ill start actuall ser!er installation.

Step #
Just "aitG until racle starts doing required con%iguration.

TUTORIALSPOINT Simply Easy Learning

Page 7

Step $
3ere racle installation "ill copy required con%iguration %ilesG so Dindly 9ust "ait and "atch5

TUTORIALSPOINT Simply Easy Learning

Page 8

Step 1%
nce e!erything is doneG you "ill ha!e %ollo"ing dialogue 8o0. Just clicD come out. $ 8utton and

TUTORIALSPOINT Simply Easy Learning

Page 9

Step 11
nce your installation is doneG you "ill ha!e %ollo"ing %inal "indo".

TUTORIALSPOINT Simply Easy Learning

Page 1

F&na' Step
6% e!erything has 8een done success%ully then its time to !eri%y your installation. At your command prompt use the %ollo"ing command i% you are using 4indo"s5 sqlplus "/ as sysdba" 6% e!erything is %ineG you should ha!e SQL prompt "here you "ill "rite your PL/SQL commands and scripts5

TUTORIALSPOINT Simply Easy Learning

Page 11

Te(t )d&tor
?unning large programs %rom command prompt may land you in inad!ertently losing some o% the "orD. So a 8etter option is to use command %iles. To use the command %iles5

etc.

Type your code in a te0t editorG liDe NotepadG NotepadKG or 'ditPlus

Sa!e the %ile "ith the .sql e0tension in the home directory. Launch SQLHPlus command prompt %rom the directory "here you created your PL/SQL

%ile.

Type L%ileFname at the SQLHPlus command prompt to e0ecute your program. 6% you are not using a %ile to e0ecute PL/SQL scriptsG then simply copy your PL/SQL code and then right clicD on the 8lacD "indo" ha!ing SQL prompt and use paste option to paste complete code at the command prompt. $inallyG 9ust press enter to e0ecute the codeG i% it is not already e0ecuted.

TUTORIALSPOINT Simply Easy Learning

Page 12

CHAPTE R

Basic Syntax
This chapter describes the basic syntax followed:

P
# &

L/SQL is a 8locD<structured languageG meaning that PL/SQL programs are di!ided and

"ritten in logical 8locDs o% code. 'ach 8locD consists o% three su8<parts5 %.N. %ections & Description Declarations This section starts "ith the Dey"ord D'C()R'. 6t is an optional section and de%ines all !aria8lesG cursorsG su8programsG and other elements to 8e used in the program. 'xecutable Co**ands This section is enclosed 8et"een the Dey"ords !'+,N and 'ND and it is a mandatory section. 6t consists o% the e0ecuta8le PL/SQL statements o% the program. 6t should ha!e at least one e0ecuta8le line o% codeG "hich may 8e 9ust a N7LL command to indicate that nothing should 8e e0ecuted. 'xception -andling This section section starts "ith the Dey"ord '.C'/0, N. This section is again optional and contains e0ception:s; that handle errors in the program.

'!ery PL/SQL statement end "ith a semicolon 123. PL/SQL 8locDs can 8e nested "ithin other PL/SQL 8locDs using !'+,N and 'ND. 3ere is the 8asic structure o% a PL/SQL 8locD5 DECLARE <declarations section> BEGIN <e ecutable co!!and"s#> E$CE%&I'N <e ception (andlin)> END*

T*e +,e''o -or'd+ )(a.p'e/


DECLARE !essa)e +arc(ar,",-#./ 01ello2 3orld40* BEGIN db!s5output6put5line"!essa)e#*

TUTORIALSPOINT Simply Easy Learning

Page 13

END* / The end2 line signals the end o% the PL/SQL 8locD. To run the code %rom SQL command lineG you may need to type 4 at the 8eginning o% the %irst 8lanD line a%ter the last line o% the code. 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 1ello 3orld %L/78L procedure success9ully co!pleted6

T*e PL/SQL Ident&f&ers


PL/SQL identi%iers are constantsG !aria8lesG e0ceptionsG proceduresG cursorsG and reser!ed "ords. The identi%iers consist o% a letter optionally %ollo"ed 8y more lettersG numeralsG dollar signsG underscoresG and num8er signs and should not e0ceed (/ characters. 1y de%aultG identifiers are not case5sensiti6e. So you can use integer or ,N0'+'R to represent a numeric !alue. Eou cannot use a reser!ed Dey"ord as an identi%ier.

T*e PL/SQL 0e'&.&ters


A delimiter is a sym8ol "ith a special meaning. $ollo"ing is the list o% delimiters in PL/SQL5 Deli*iter 78 58 98 4 : ; . 183 < 8 = > ? 2 <> >@ AA 99 BB8 @@ Description AdditionG su8traction/negationG multiplicationG di!ision Attri8ute indicator Character string delimiter Component selector '0pression or list delimiter 3ost !aria8le indicator 6tem separator Quoted identi%ier delimiter ?elational operator ?emote access indicator Statement terminator Assignment operator Association operator Concatenation operator '0ponentiation operator La8el delimiter :8egin and end;

TUTORIALSPOINT Simply Easy Learning

Page 14

498 94 55 .. B8 @8 B>8 @> B@8 ;>8 C>8 D>

Culti<line comment delimiter :8egin and end; Single<line comment indicator ?ange operator ?elational operators Di%%erent !ersions o% N T 'Q7AL

T*e PL/SQL 1o..ents


Program comments are e0planatory statements that you can include in the PL/SQL code that you "rite and helps anyone reading it2s source code. All programming languages allo" %or some %orm o% comments. The PL/SQL supports single line and multi<line comments. All characters a!aila8le inside any comment are ignored 8y PL/SQL compiler. The PL/SQL single<line comments start "ith the delimiter 55:dou8le hyphen; and multi<line comments are enclosed 8y /H and H/. DECLARE

:: +ariable declaration
!essa)e BEGIN +arc(ar,",-#./ 01ello2 3orld40*

/; ; %L/78L e ecutable state!ent"s# ;/


db!s5output6put5line"!essa)e#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 1ello 3orld %L/78L procedure success9ully co!pleted6

PL/SQL Progra. Un&ts


A PL/SQL unit is any one o% the %ollo"ing5

PL/SQL 8locD $unction PacDage PacDage 8ody Procedure Trigger

TUTORIALSPOINT

Simply Easy Learning

Page 15

Type Type 8ody

'ach o% these units "ill 8e discussed in the %orthcoming chapters.

TUTORIALSPOINT Simply Easy Learning

Page 16

CHAPTE R

ata Ty!es
This chapter describes the Data Types used under PL/SQL:

"

P
Scalar Large

L/SQL !aria8lesG constants and parameters must ha!e a !alid data types "hich speci%ies

a storage %ormatG constraintsG and !alid range o% !alues. This tutorial "ill taDe you through %C)()R and ( ! data types a!aila8le in PL/SQL and other t"o data types "ill 8e co!ered in other chapters. CategorE Description Single !alues "ith no internal componentsG such as a N7C1'?G DAT'G or 1 L'AN. 89ect :L 1; Pointers to large o89ects that are stored separately %rom other data itemsG such as te0tG graphic imagesG !ideo clipsG and sound "a!e%orms. Data items that ha!e internal components that can 8e accessed indi!idually. $or e0ampleG collections and records. Pointers to other data items.

Composite ?e%erence

PL/SQL S2a'ar 0ata T3pes and Su4t3pes


PL/SQL Scalar Data Types and Su8types come under the %ollo"ing categories5 Date 0Epe Numeric Character 1oolean Datetime Description Numeric !aluesG on "hich arithmetic operations are per%ormed. Alphanumeric !alues that represent single characters or strings o% characters. Logical !aluesG on "hich logical operations are per%ormed. Dates and times.

PL/SQL pro!ides su8types o% data types. $or e0ampleG the data type N7C1'? has a su8type called 6NT'B'?. Eou can use su8types in your PL/SQL program to maDe the data types compati8le "ith data types in other programs "hile em8edding PL/SQL code in another programG such as a Ja!a program.

TUTORIALSPOINT Simply Easy Learning

Page 17

PL/SQL Nu.er&2 0ata T3pes and Su4t3pes


$ollo"ing is the detail o% PL/SQL pre<de%ined numeric data types and their su8<types5 Data 0Epe PLSF6NT'B'? 16NA?EF6NT'B'? 16NA?EF$L AT 16NA?EFD 71L' N7C1'?:precG scale; D'C:precG scale; D'C6CAL:precG scale; Description Signed integer in range <&G#),G)-(G+)- through &G#),G)-(G+),G represented in (& 8its Signed integer in range <&G#),G)-(G+)- through &G#),G)-(G+),G represented in (& 8its Single<precision 6''' ,*)<%ormat %loating<point num8er Dou8le<precision 6''' ,*)<%ormat %loating<point num8er $i0ed<point or %loating<point num8er "ith a8solute !alue in range #'<#(/ to :8ut not including; #./'#&+. A N7C1'? !aria8le can also represent /. ANS6 speci%ic %i0ed<point type "ith ma0imum precision o% (- decimal digits. 61C speci%ic %i0ed<point type "ith ma0imum precision o% (- decimal digits.

N7C'?6C:preG secale; $loating type "ith ma0imum precision o% (- decimal digits. D 71L' P?'C6S6 N $L AT 6NT 6NT'B'? SCALL6NT ?'AL ANS6 speci%ic %loating<point type "ith ma0imum precision o% #&+ 8inary digits :appro0imately (- decimal digits; ANS6 and 61C speci%ic %loating<point type "ith ma0imum precision o% #&+ 8inary digits :appro0imately (- decimal digits; ANS6 speci%ic integer type "ith ma0imum precision o% (- decimal digits ANS6 and 61C speci%ic integer type "ith ma0imum precision o% (decimal digits ANS6 and 61C speci%ic integer type "ith ma0imum precision o% (decimal digits $loating<point type "ith ma0imum precision o% +( 8inary digits :appro0imately #- decimal digits;

$ollo"ing is a !alid declaration5 DECLARE nu!< IN&EGER* nu!, REAL* nu!= D'>BLE %RECI7I'N* BEGIN null* END* / 4hen the a8o!e code is compiled and e0ecutedG it produces %ollo"ing result5 %L/78L procedure success9ully co!pleted

TUTORIALSPOINT Simply Easy Learning

Page 18

PL/SQL 1*ara2ter 0ata T3pes and Su4t3pes


$ollo"ing is the detail o% PL/SQL pre<de%ined character data types and their su8<types5 Data 0Epe C3A? =A?C3A?& ?A4 NC3A? N=A?C3A?& L NB L NB ?A4 ? 46D 7? 46D Description $i0ed<length character string "ith ma0imum si>e o% (&G,+, 8ytes =aria8le<length character string "ith ma0imum si>e o% (&G,+, 8ytes =aria8le<length 8inary or 8yte string "ith ma0imum si>e o% (&G,+, 8ytesG not interpreted 8y PL/SQL $i0ed<length national character string "ith ma0imum si>e o% (&G,+, 8ytes =aria8le<length national character string "ith ma0imum si>e o% (&G,+, 8ytes =aria8le<length character string "ith ma0imum si>e o% (&G,+/ 8ytes =aria8le<length 8inary or 8yte string "ith ma0imum si>e o% (&G,+/ 8ytesG not interpreted 8y PL/SQL Physical ro" identi%ierG the address o% a ro" in an ordinary ta8le 7ni!ersal ro" identi%ier :physicalG logicalG or %oreign ro" identi%ier;

PL/SQL 5oo'ean 0ata T3pes


The ! (')N data type stores logical !alues that are used in logical operations. The logical !alues are the 1oolean !alues T?7' and $ALS' and the !alue N7LL. 3o"e!erG SQL has no data type equi!alent to 1 8e used in5 L'AN. There%ore 1oolean !alues cannot

SQL statements 1uilt<in SQL %unctions :such as T FC3A?; PL/SQL %unctions in!oDed %rom SQL statements

PL/SQL 0atet&.e and Interva' T3pes


The D)0' datatype to store %i0ed<length datetimesG "hich include the time o% day in seconds since midnight. =alid dates range %rom January #G ),#& 1C to Decem8er (#G .... AD. The de%ault date %ormat is set 8y the racle initiali>ation parameter NLSFDAT'F$ ?CAT. $or e0ampleG the de%ault might 8e 2DD<C N<EE2G "hich includes a t"o<digit num8er %or the day o% the monthG an a88re!iation o% the month nameG and the last t"o digits o% the yearG %or e0ampleG /#< CT<#&. 'ach DAT' includes the centuryG yearG monthG dayG hourG minuteG and second. The %ollo"ing ta8le sho"s the !alid !alues %or each %ield5

TUTORIALSPOINT Simply Easy Learning

Page 19

"ield Na*e E'A? C NT3

Falid Dateti*e Falues Falid ,nter6al Falues <),#& to .... :e0cluding year /; /# to #& Any non>ero integer / to ##

DAE

/# to (# :limited 8y the !alues o% C NT3 and E'A?G according to the Any non>ero integer rules o% the calendar %or the locale; // to &( // to *. // to *...:n;G "here .:n; is the precision o% time %ractional seconds / to &( / to *. / to *...:n;G "here .:n; is the precision o% inter!al %ractional seconds

3 7? C6N7T' S'C ND

T6C'M N'F3 7?

<#& to #) :range accommodates daylight Not applica8le sa!ings time changes; Not applica8le

T6C'M N'FC6N7T' // to *.

$ound in the dynamic T6C'M N'F?'B6 N per%ormance !ie" Not applica8le =NT6C'M N'FNAC'S T6C'M N'FA11? $ound in the dynamic Not applica8le per%ormance !ie" =NT6C'M N'FNAC'S

PL/SQL Large O46e2t 0ata T3pes

7LO58

Large o89ect :L 1; data types re%er large to data items such as te0tG graphic imagesG !ideo clipsG and sound "a!e%orms. L 1 data types allo" e%%icientG randomG piece"ise access to this data. $ollo"ing are the prede%ined PL/SQL L 1 data types5 Data 0Epe 1$6L' Description 7sed to store large 8inary o89ects in operating system %iles outside the data8ase. 7sed to store large 8inary o89ects in the data8ase. %ize System<dependent. Cannot e0ceed ) giga8ytes :B1;. - to #&- tera8ytes :T1;

1L 1 CL 1

7sed to store large 8locDs o% - to #&- T1 character data in the data8ase. 7sed to store large 8locDs o% NC3A? data in the - to #&- T1 data8ase.

NCL 1

TUTORIALSPOINT

Simply Easy Learning

Page 2

PL/SQL User90ef&ned Su4t3pes


A su8type is a su8set o% another data typeG "hich is called its 8ase type. A su8type has the same !alid operations as its 8ase typeG 8ut only a su8set o% its !alid !alues. PL/SQL prede%ines se!eral su8types in pacDage STANDA?D. $or e0ampleG PL/SQL prede%ines the su8types C3A?ACT'? and 6NT'B'? as %ollo"s5 7>B&?%E C1ARAC&ER I7 C1AR* 7>B&?%E IN&EGER I7 N>@BER"=A2-#* Eou can de%ine and use your o"n su8types. The %ollo"ing program illustrates de%ining and using a user<de%ined su8type5 DECLARE 7>B&?%E na!e I7 c(ar",-#* 7>B&?%E !essa)e I7 +arc(ar,"<--#* salutation na!e* )reetin)s !essa)e* BEGIN salutation ./ 0Reader 0* )reetin)s ./ 03elco!e to t(e 3orld o9 %L/78L0* db!s5output6put5line"01ello 0 BB salutation BB )reetin)s#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 1ello Reader 3elco!e to t(e 3orld o9 %L/78L %L/78L procedure success9ully co!pleted6

NULLs PL/SQL

&n

PL/SQL N7LL !alues represent missing or unDno"n data and they are not an integerG a characterG or any other speci%ic data type. Note that N7LL is not the same as an empty data string or the null character !alue 2O/2. A null can 8e assigned 8ut it cannot 8e equated "ith anythingG including itsel%.

TUTORIALSPOINT

Simply Easy Learning

Page 21

CHAPTER

&

#aria$%e s
This chapter describes variables used: the

!aria8le is nothing 8ut a name gi!en to a storage area that our programs can

manipulate. 'ach !aria8le in PL/SQL has a speci%ic data typeG "hich determines the si>e and layout o% the !aria8le2s memoryI the range o% !alues that can 8e stored "ithin that memory and the set o% operations that can 8e applied to the !aria8le. The name o% a PL/SQL !aria8le consist o% a letter optionally %ollo"ed 8y more lettersG numeralsG dollar signsG underscoresG and num8er signs and should not e0ceed (/ characters. 1y de%aultG !aria8le names are not case<sensiti!e. Eou cannot use a reser!ed PL/SQL Dey"ords as a !aria8le name. PL/SQL programming language allo"s to de%ine !arious type o% !aria8les "hich "e "ill co!er in su8sequent chapters liDe date time data typesG recordsG collections etc. $or this chapterG let us study only 8asic !aria8le types.

:ar&a4'e PL/SQL

0e2'arat&on

&n

PL/SQL !aria8les must 8e declared in the declaration section or in a pacDage as a glo8al !aria8le. 4hen you declare a !aria8leG PL/SQL allocates memory %or the !aria8le2s !alue and the storage location is identi%ied 8y the !aria8le name. The synta0 %or declaring a !aria8le is5
+ariable5na!e CC'N7&AN&D datatype CN'& N>LLD C./ B DEEA>L& initial5+alueD

4hereG variable_name is a !alid identi%ier in PL/SQLG datatype must 8e a !alid PL/SQL data type or any user de%ined data type "hich "e already ha!e discussed in last chapter. Some !alid !aria8le declarations along "ith their de%inition are sho"n 8elo"5 sales nu!ber"<-2 ,#* pi C'N7&AN& double precision ./ =6<F<G* na!e +arc(ar,",G#* address +arc(ar,"<--#*

TUTORIALSPOINT Simply Easy Learning

Page 22

4hen you pro!ide a si>eG scale or precision limit "ith the data typeG it is called a constrained declaration. Constrained declarations require less memory than unconstrained declarationsG $or e0ample5 sales nu!ber"<-2 ,#* na!e +arc(ar,",G#* address +arc(ar,"<--#*

In&t&a'&;&ng PL/SQL

:ar&a4'es

&n

4hene!er you declare a !aria8leG PL/SQL assigns it a de%ault !alue o% N7LL. 6% you "ant to initiali>e a !aria8le "ith a !alue other than the N7LL !alueG you can do so during the declarationG using either o% the %ollo"ing5

The D'")G(0 Dey"ord The assign*ent operator


$or e0ample5 counter binary5inte)er ./ -* )reetin)s +arc(ar,",-# DEEA>L& 01a+e a Good Day0* Eou can also speci%y that a !aria8le should not ha!e a NG(( !alue using the N 0 NG(( constraint. 6% you use the N T N7LL constraintG you must e0plicitly assign an initial !alue %or that !aria8le. 6t is a good programming practice to initiali>e !aria8les properly other"iseG sometime program "ould produce une0pected result. Try %ollo"ing e0ample "hich maDes use o% !arious types o% !aria8les5 DECLARE a inte)er ./ <-* b inte)er ./ ,-* c inte)er* 9 real* BEGIN c ./ a H b* db!s5output6put5line"0Ialue o9 c. 0 BB c#* 9 ./ J-6-/=6-* db!s5output6put5line"0Ialue o9 9. 0 BB 9#* END* / 4hen the a8o!e code is e0ecutedG it produces %ollo"ing result5 Ialue o9 c. =Ialue o9 9. ,=6================== %L/78L procedure success9ully co!pleted6

:ar&a4'e S2ope &n PL/SQL


PL/SQL allo"s the nesting o% 1locDs i.e.G each program 8locD may contain another inner 8locD. 6% a !aria8le is declared "ithin an inner 8locDG it is not accessi8le to the outer 8locD. 3o"e!erG i% a

TUTORIALSPOINT Simply Easy Learning

Page 23

!aria8le is declared and accessi8le to an outer 1locDG it is also accessi8le to all nested inner 1locDs. There are t"o types o% !aria8le scope5

(ocal 6ariables < !aria8les declared in an inner 8locD and not accessi8le to outer 8locDs. +lobal 6ariables < !aria8les declared in the outermost 8locD or a pacDage.
$ollo"ing e0ample sho"s the usage o% (ocal and +lobal !aria8les in its simple %orm5 DECLARE

nu!< nu!ber ./ KG* nu!, nu!ber ./ AG* BEGIN db!s5output6put5line"0'uter Iariable nu!<. 0 BB nu!<#* db!s5output6put5line"0'uter Iariable nu!,. 0 BB nu!,#* DECLARE nu!< nu!ber ./ <KG* nu!, nu!ber ./ <AG* BEGIN db!s5output6put5line"0Inner Iariable nu!<. 0 BB nu!<#* db!s5output6put5line"0Inner Iariable nu!,. 0 BB nu!,#* END* END* / 4hen the a8o!e code is e0ecutedG it produces %ollo"ing result5 'uter 'uter Inner Inner Iariable Iariable Iariable Iariable nu!<. nu!,. nu!<. nu!,. KG AG <KG <AG

:: Global +ariables

:: Local +ariables

%L/78L procedure success9ully co!pleted6

Ass&gn&ng SQL Quer3 Resu'ts to PL/SQL :ar&a4'es


Eou can use the S'L'CT 6NT statement o% SQL to assign !alues to PL/SQL !aria8les. $or each item in the S'L'CT listG there must 8e a correspondingG type<compati8le !aria8le in the 6NT list. The %ollo"ing e0ample illustrates the concept5 Let us create a ta8le named C7ST C'?S5 :"or %H( state*ents please look at t#e

%H(

tutorial;
CREA&E &ABLE C>7&'@ER7" ID IN& N'& N>LL2 NA@E IARC1AR ",-# N'& N>LL2 AGE IN& N'& N>LL2 ADDRE77 C1AR ",G#2 7ALAR? DECI@AL "<A2 ,#2 %RI@AR? LE? "ID# #* &able Created Ne0tG let us insert some !alues in the ta8le5

TUTORIALSPOINT Simply Easy Learning

Page 24

IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "<2 0Ra!es(02 =,2 0A(!edabad02 ,---6-- #* IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 ",2 0L(ilan02 ,G2 0Del(i02 <G--6-- #* IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "=2 0Maus(iM02 ,=2 0Lota02 ,---6-- #* IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "F2 0C(aitali02 ,G2 0@u!bai02 NG--6-- #* IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "G2 01ardiM02 ,J2 0B(opal02 AG--6-- #* IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "N2 0Lo!al02 ,,2 0@%02 FG--6-- #* The %ollo"ing program assigns !alues %rom the a8o!e ta8le to PL/SQL !aria8les using the S'L'CT 6NT clause o% SQL5 DECLARE c5id custo!ers6idOtype ./ <* c5na!e custo!ers6na!eOtype* c5addr custo!ers6addressOtype* c5sal custo!ers6salaryOtype* BEGIN 7ELEC& na!e2 address2 salary IN&' c5na!e2 c5addr2 c5sal ER'@ custo!ers 31ERE id / c5id* db!s5output6put5line "0Custo!er 0 BBc5na!e BB 0 9ro! 0 BB c5addr BB 0 earns 0 BB c5sal#* END* / 4hen the a8o!e code is e0ecutedG it produces %ollo"ing result5 Custo!er Ra!es( 9ro! A(!edabad earns ,--%L/78L procedure co!pleted success9ully

TUTORIALSPOINT Simply Easy Learning

Page 25

CHAPTER

'

Constant s
This chapter shows the usage of constants:

constant holds a !alue that once declaredG does not change in the program. A

constant declaration speci%ies its nameG data typeG and !alueG and allocates storage %or it. The declaration can also impose the N T N7LL constraint.

0e2'ar&ng 1onstant

A constant is declared using the C NSTANT Dey"ord. 6t requires an initial !alue and does not allo" that !alue to 8e changedG $or e0ample5 %I C'N7&AN& N>@BER ./ =6<F<GK,NGF* DECLARE :: constant declaration pi constant nu!ber ./ =6<F<GK,NGF* :: ot(er declarations radius nu!ber"G2,#* dia nu!ber"G2,#* circu!9erence nu!ber"J2 ,#* area nu!ber "<-2 ,#* BEGIN :: processin) radius ./ K6G* dia ./ radius ; ,* circu!9erence ./ ,6- ; pi ; radius* area ./ pi ; radius ; radius* :: output db!s5output6put5line"0Radius. 0 BB radius#* db!s5output6put5line"0Dia!eter. 0 BB dia#* db!s5output6put5line"0Circu!9erence. 0 BB circu!9erence#* db!s5output6put5line"0Area. 0 BB area#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 Radius. K6G

Dia!eter. <K

TUTORIALSPOINT Simply Easy Learning

Page 26

Circu!9erence. GK6NK Area. ,A=6G= %l/78L procedure success9ully co!pleted6

T*e PL/SQL L&tera's


A literal is an e0plicit numericG characterG stringG or 1oolean !alue not represented 8y an identi%ier. $or e0ampleG T?7'G ,-+G N7LLG 2tutorialspoint2 are all literals o% type 1ooleanG num8erG or string. PL/SQLG literals are case<sensiti!e. PL/SQL supports the %ollo"ing Dinds o% literals5

Numeric Literals Character Literals String Literals 1 L'AN Literals

Date and Time Literals

The %ollo"ing ta8le pro!ides e0amples %rom all these categories o% literal !alues. (iteral 0Epe Numeric Literals Character Literals String Literals 1 L'AN Literals 'xa*ple< /*/ ,- <#) / K(&,+, +.+++, /./ <#&./ (.#)#*. K,-//.// +'* #./'<- (.#)#*.e/ <#'(- <..*e<( 2A2 2P2 2.2 2 2 2>2 2:2 23elloG "orldQ2 2Tutorials Point2 2#.<N =<#&2 T?7'G $ALS'G and N7LL. DAT' 2#.,-<#&<&*2I T6C'STACP 2&/#&<#/<&. #&5/#5/#2I

Date and Time Literals

To em8ed single quotes "ithin a string literalG place t"o single quotes ne0t to each other as sho"n 8elo"5 DECLARE !essa)e +arc(ar,",-#./ 00&(at00s tutorialspoint6co!400* BEGIN db!s5output6put5line"!essa)e#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &(at0s tutorialspoint6co!4 %L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 27

CHAPTE R

O!erator s

This chapter describes the different operators used under PL/SQL:

n operator is a sym8ol that tells the compiler to per%orm speci%ic mathematical or

logical manipulations. PL/SQL language is rich in 8uilt<in operators and pro!ides %ollo"ing type o% operators5 Arithmetic operators ?elational operators Comparison operators Logical operators String operators

This tutorial "ill e0plain the arithmeticG relationalG comparison and logical operators one 8y one. The String operators "ill 8e discussed under the chapter5 /(4%H( 5 %trings.

Ar&t*.et&2 Operators
$ollo"ing ta8le sho"s all the arithmetic operators supported 8y PL/SQL. Assume !aria8le A holds #/ and !aria8le 1 holds * then5 perator Description K < H / HH Adds t"o operands Su8tracts second operand %rom the %irst Cultiply 8oth operands Di!ide numerator 8y de<numerator '0ponentiation operatorG raises one operand to the po"er o% other 'xa*ple A K 1 "ill gi!e #* A < 1 "ill gi!e * A H 1 "ill gi!e */ A / 1 "ill gi!e & A HH 1 "ill gi!e #/////

TUTORIALSPOINT Simply Easy Learning

Page 28

)(a.p'e/
BEGIN db!s5output6put5line" db!s5output6put5line" db!s5output6put5line" db!s5output6put5line" db!s5output6put5line" END* / <<<<<H G#* : G#* ; G#* / G#* ;; G#*

4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 <G G G, <----%L/78L procedure success9ully co!pleted6

Re'at&ona' Operators
?elational operators compare t"o e0pressions or !alues and return a 1oolean result. $ollo"ing ta8le sho"s all the relational operators supported 8y PL/SQL. Assume !aria8le A holds #/ and !aria8le 1 holds &/ then5 perator Description R QR ST UR T S TR SR ChecDs i% the !alue o% t"o operands is equal or notG i% yes then condition 8ecomes true. ChecDs i% the !alue o% t"o operands is equal or notG i% !alues are not equal then condition 8ecomes true. ChecDs i% the !alue o% le%t operand is greater than the !alue o% right operandG i% yes then condition 8ecomes true. ChecDs i% the !alue o% le%t operand is less than the !alue o% right operandG i% yes then condition 8ecomes true. ChecDs i% the !alue o% le%t operand is greater than or equal to the !alue o% right operandG i% yes then condition 8ecomes true. ChecDs i% the !alue o% le%t operand is less than or equal to the !alue o% right operandG i% yes then condition 8ecomes true. 'xa*ple :A R 1; is not true. :A QR 1; is true. :A T 1; is not true. :A S 1; is true. :A TR 1; is not true. :A SR 1; is true.

)(a.p'e/
DECLARE a nu!ber ",# ./ ,<* b nu!ber ",# ./ <-* BEGIN IE "a / b# t(en db!s5output6put5line"0Line < : a is equal to b0#* EL7E db!s5output6put5line"0Line < : a is not equal to b0#* END IE*

TUTORIALSPOINT

Simply Easy Learning

Page 29

IE "a < b# t(en db!s5output6put5line"0Line , : a is less t(an b0#* EL7E db!s5output6put5line"0Line , : a is not less t(an b0#* END IE* IE " a > b # &1EN db!s5output6put5line"0Line = : a is )reater t(an b0#* EL7E db!s5output6put5line"0Line = : a is not )reater t(an b0#* END IE* :: Lets c(an)e +alue o9 a and b a ./ G* b ./ ,-* IE " a </ b # &1EN db!s5output6put5line"0Line F : a is eit(er equal or less t(an b0#* END IE* IE " b >/ a # &1EN db!s5output6put5line"0Line G : b is eit(er equal or )reater t(an a0#* END IE* IE " a <> b # &1EN db!s5output6put5line"0Line N : a is not equal to b0#* EL7E db!s5output6put5line"0Line N : a is equal to b0#* END IE* END* /

4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 Line Line Line Line Line Line < , = F G N : : : : : : a a a a b a is is is is is is not equal to b not less t(an b )reater t(an b eit(er equal or less t(an b eit(er equal or )reater t(an a not equal to b

%L/78L procedure success9ully co!pleted

1o.par&son Operators
Comparison operators are used %or comparing one e0pression to another. The result is al"ays either T?7'G $ALS'G ? N7LL. perator Description 'xa*ple 6% 2Mara Ali2 liDe 2MP AFi2 returns a 1oolean trueG "hereasG 2Nuha Ali2 liDe 2MP AFi2 returns a 1oolean %alse. 6% 0 R #/ thenG 0 8et"een * and &/

L6@'

The L6@' operator compares a characterG stringG or CL 1 !alue to a pattern and returns T?7' i% the !alue matches the pattern and $ALS' i% it does not.

The 1'T4''N operator tests "hether a !alue lies in a 1'T4''N speci%ied range. 0 1'T4''N a AND 8 means that 0 TR a

TUTORIALSPOINT Simply Easy Learning

Page 3

and 0 SR 8.

returns trueG 0 8et"een * and #/ returns trueG 8ut 0 8et"een ## and &/ returns %alse.

6N

6% 0 R 2m2 thenG 0 in :2a2G 282G 2c2; returns The 6N operator tests set mem8ership. 0 6N :set; means that 8oolean %alse 8ut 0 in 0 is equal to any mem8er o% set. :2m2G 2n2G 2o2; returns 1oolean true. The 6S N7LL operator returns the 1 L'AN !alue T?7' i% its operand is N7LL or $ALS' i% it is not N7LL. Comparisons in!ol!ing N7LL !alues al"ays yield N7LL. 6% 0 R 2m2G then 20 is null2 returns 1oolean %alse.

6S N7LL

LI<) Operator/
This program tests the L6@' operatorG though you "ill learn ho" to "rite procedure in PL/SQLG 8ut 62m going to use a small procedure() to sho" the %unctionality o% L6@' operator5 DECLARE %R'CED>RE co!pare "+alue +arc(ar,2 pattern +arc(ar, # is BEGIN IE +alue LILE pattern &1EN db!s5output6put5line "0&rue0#* EL7E db!s5output6put5line "0Ealse0#* END IE* END* BEGIN co!pare"0Para Ali02 0POA5i0#* co!pare"0Nu(a Ali02 0POA5i0#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &rue Ealse %L/78L procedure success9ully co!pleted6

5)T-))N Operator/
The %ollo"ing program sho"s the usage o% the 1'T4''N operator5 DECLARE nu!ber",# ./ <-* BEGIN IE " betQeen G and ,-# &1EN db!s5output6put5line"0&rue0#* EL7E db!s5output6put5line"0Ealse0#* END IE* IE " BE&3EEN G AND <-# &1EN db!s5output6put5line"0&rue0#*

TUTORIALSPOINT Simply Easy Learning

Page 31

EL7E db!s5output6put5line"0Ealse0#* END IE* IE " BE&3EEN << AND ,-# &1EN db!s5output6put5line"0&rue0#* EL7E db!s5output6put5line"0Ealse0#* END IE* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &rue &rue Ealse %L/78L procedure success9ully co!pleted6

IN and IS NULL Operators/


The %ollo"ing program sho"s the usage o% 6N and 6S N7LL operators5 DECLARE letter +arc(ar,"<# ./ 0!0* BEGIN IE "letter in "0a02 0b02 0c0## &1EN db!s5output6put5line"0&rue0#* EL7E db!s5output6put5line"0Ealse0#* END IE* IE "letter in "0!02 0n02 0o0## &1EN db!s5output6put5line"0&rue0#* EL7E db!s5output6put5line"0Ealse0#* END IE* IE "letter is null# &1EN db!s5output6put5line"0&rue0#* EL7E db!s5output6put5line"0Ealse0#* END IE* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 Ealse &rue Ealse %L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 32

Log&2a' Operators
$ollo"ing ta8le sho"s the Logical operators supported 8y PL/SQL. All these operators "orD on 1oolean operands and produces 1oolean results. Assume !aria8le A holds true and !aria8le 1 holds %alse then5 perator Description and or Called logical AND operator. 6% 8oth the operands are true then condition 8ecomes true. Called logical ? perator. 6% any o% the t"o operands is true then condition 8ecomes true. Called logical N T not perator. 7sed to re!erse the logical state o% its operand. 6% a condition is true then Logical N T operator "ill maDe it %alse. 'xa*ple :A and 1; is %alse. :A or 1; is true. not :A and 1; is true.

)(a.p'e/
DECLARE a boolean ./ true* b boolean ./ 9alse* BEGIN IE "a AND b# &1EN db!s5output6put5line"0Line END IE* IE "a 'R b# &1EN db!s5output6put5line"0Line END IE* IE "N'& a# &1EN db!s5output6put5line"0Line EL7E db!s5output6put5line"0Line END IE* IE "N'& b# &1EN db!s5output6put5line"0Line EL7E db!s5output6put5line"0Line END IE* END* /

< : Condition is true0#* , : Condition is true0#* = : a is not true0#* = : a is true0#* F : b is not true0#* F : b is true0#*

4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 Line , : Condition is true Line = : a is true Line F : b is not true %L/78L procedure success9ully co!pleted6

PL/SQL Pre2eden2e

Operator

perator precedence determines the grouping o% terms in an e0pression. This a%%ects ho" an e0pression is e!aluated. Certain operators ha!e higher precedence than othersI %or e0ampleG the multiplication operator has higher precedence than the addition operator5

TUTORIALSPOINT Simply Easy Learning

Page 33

$or e0ample 0 R , K ( H &I 3ere 0 is assigned #(G not &/ 8ecause operator H has higher precedence than K so it %irst get multiplied "ith (H& and then adds into ,. 3ere operators "ith the highest precedence appear at the top o% the ta8leG those "ith the lo"est appear at the 8ottom. 4ithin an e0pressionG higher precedence operators "ill 8e e!aluated %irst. perator HH KG < HG / KG <G VV RG SG TG SRG TRG STG QRG URG WRG 6S N7LLG L6@'G 1'T4''NG 6N N T AND ? peration e0ponentiation identityG negation multiplicationG di!ision additionG su8tractionG concatenation comparison logical negation con9unction inclusion

)(a.p'e/
Try %ollo"ing e0ample to understand the operator precedence a!aila8le in PL/SQL5 DECLARE a nu!ber",# ./ ,-* b nu!ber",# ./ <-* c nu!ber",# ./ <G* d nu!ber",# ./ G* e nu!ber",# * BEGIN e ./ "a H b# ; c / d* :: " =- ; <G # / G db!s5output6put5line"0Ialue o9 "a H b# ; c / d is . 0BB e #* e ./ ""a H b# ; c# / d* :: "=- ; <G # / G db!s5output6put5line"0Ialue o9 ""a H b# ; c# / d is e ./ "a H b# ; "c / d#* :: "=-# ; "<G/G# db!s5output6put5line"0Ialue o9 "a H b# ; "c / d# is e ./ a H "b ; c# / d* :: ,- H "<G-/G# db!s5output6put5line"0Ialue o9 a H "b ; c# / d is END* / . 0 BB . 0BB e #* e #* e #*

. 0 BB

4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 Ialue Ialue Ialue Ialue o9 o9 o9 o9 "a H b# ; c / d is . K""a H b# ; c# / d is . K"a H b# ; "c / d# is . Ka H "b ; c# / d is . G-

%L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 34

CHAPTE R

Con)ition s
This chapter describes the Decision !a"ing Structure:

ecision maDing structures require that the programmer speci%y one or more conditions

to 8e e!aluated or tested 8y the programG along "ith a statement or statements to 8e e0ecuted i% the condition is determined to 8e trueG and optionallyG other statements to 8e e0ecuted i% the condition is determined to 8e %alse. $ollo"ing is the general %rom o% a typical conditional :i.e. decision maDing; structure %ound in most o% the programming languages5

PL/SQL programming language pro!ides %ollo"ing types o% decision maDing statements. ClicD the %ollo"ing linDs to checD their detail.

TUTORIALSPOINT Simply Easy Learning

Page 35

%tate*ent

Description The ," state*ent associates a condition "ith a sequence o% statements enclosed 8y the Dey"ords 0-'N and 'ND ,". 6% the condition is trueG the statements get e0ecuted and i% the condition is %alse or N7LL then the 6$ statement does nothing. ," state*ent adds the Dey"ord '(%' %ollo"ed 8y an alternati!e sequence o% statement. 6% the condition is %alse or N7LL G then only the alternati!e sequence o% statements get e0ecuted. 6t ensures that either o% the sequence o% statements is e0ecuted. 6t allo"s you to choose 8et"een se!eral alternati!es. LiDe the 6$ statementG the C)%' state*ent selects one sequence o% statements to e0ecute. 3o"e!erG to select the sequenceG the CAS' statement uses a selector rather than multiple 1oolean e0pressions. A selector is an e0pression "hose !alue is used to select one o% se!eral alternati!es. The searched CAS' statement #as no selectorG and it2s 43'N clauses contain search conditions that yield 1oolean !alues. Eou can use one ,"50-'N or ,"50-'N5'(%," statement inside another ,"50-'N or ,"50-'N5'(%," statement:s;.

6$ < T3'N statement

6$<T3'N<'LS' statement

6$<T3'N<'LS6$ statement

Case statement

Searched CAS' statement

nested 6$<T3'N<'LS'

IF 9 T,)N state.ent
6t is the simplest %orm o% ," control statementG %requently used in decision maDing and changing the control %lo" o% the program e0ecution. The ," state*ent associates a condition "ith a sequence o% statements enclosed 8y the Dey"ords0-'N and 'ND ,". 6% the condition is 0RG'G the statements get e0ecuted and i% the condition is ")(%' orNG(( then the ," statement does nothing.

S3nta(/
Synta0 %or 6$<T3'N statement is5 IE condition &1EN 7* END IE* 4here condition is a 1oolean or relational condition and S is a simple or compound statement. '0ample o% an 6$<T3'N statement is5 IE "a </ ,-# &1EN c./ cH<* END IE* 6% the 8oolean e0pression condition e!aluates to true then the 8locD o% code inside the i% statement "ill 8e e0ecuted. 6% 8oolean e0pression e!aluates to %alse then the %irst set o% code a%ter the end o% the i% statement :a%ter the closing end i%; "ill 8e e0ecuted.

F'o= 0&agra./

TUTORIALSPOINT

Simply Easy Learning

Page 36

)(a.p'e 1/
Let us try a complete e0ample that "ould illustrate the concept5 DECLARE a nu!ber",# ./ <-* BEGIN a./ <-* :: c(ecM t(e boolean condition usin) i9 state!ent IE" a < ,- # &1EN :: i9 condition is true t(en print t(e 9olloQin) db!s5output6put5line"0a is less t(an ,- 0 #* END IE* db!s5output6put5line"0+alue o9 a is . 0 BB a#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 a is less t(an ,+alue o9 a is . <%L/78L procedure success9ully co!pleted6

)(a.p'e 2/
Consider "e ha!e a ta8le and %e" records in the ta8le as "e had created in PL/SQL =aria8le

T ypes
DECLARE c5id custo!ers6idOtype ./ <* c5sal custo!ers6salaryOtype*

TUTORIALSPOINT Simply Easy Learning

Page 37

BEGIN 7ELEC& salary IN&' c5sal ER'@ custo!ers 31ERE id / c5id* IE "c5sal </ ,---# &1EN >%DA&E custo!ers 7E& salary / salary H <--31ERE id / c5id* db!s5output6put5line "07alary updated0#* END IE* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 7alary updated %L/78L procedure success9ully co!pleted6

IF9T,)N9)LS) state.ent
A sequence o% ,"50-'N statements can 8e %ollo"ed 8y o% '(%' statementsG "hich e0ecutes "hen the condition is ")(%'. an optional sequence

S3nta(/
Synta0 %or the 6$<T3'N<'LS' statement is5 IE condition &1EN 7<* EL7E 7,* END IE* 4hereG S1 and S2 are di%%erent sequence o% statements. 6n the 6$<T3'N<'LS' statementsG "hen the test condition is T?7'G the statement S1 is e0ecuted and S2 is sDippedI "hen the test condition is $ALS'G then S1 is 8ypassed and statement S2 is e0ecutedG $or e0ampleG IE color / red &1EN db!s5output6put5line"0?ou (a+e c(osen a red car0# EL7E db!s5output6put5line"0%lease c(oose a color 9or your car0#* END IE* 6% the 8oolean e0pression condition e!aluates to true then the i%<then 8locD o% code "ill 8e e0ecuted other"ise the else 8locD o% code "ill 8e e0ecuted.

F'o= 0&agra./

TUTORIALSPOINT Simply Easy Learning

Page 38

)(a.p'e/
Let us try a complete e0ample that "ould illustrate the concept5 DECLARE a nu!ber"=# ./ <--* BEGIN IE" a < ,- # &1EN

:: c(ecM t(e boolean condition usin) i9 state!ent :: i9 condition is true t(en print t(e 9olloQin)

db!s5output6put5line"0a is less t(an ,- 0 #* EL7E db!s5output6put5line"0a is not less t(an ,- 0 #* END IE* db!s5output6put5line"0+alue o9 a is . 0 BB a#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 a is not less t(an ,+alue o9 a is . <-%L/78L procedure success9ully co!pleted6

IF9T,)N9)LSIF state.ent
The ,"50-'N5'(%," statement allo"s you to choose 8et"een se!eral alternati!es. An ,"5 0-'N statement can 8e %ollo"ed 8y an optional '(%,"...'(%' statement. The '(%," clause lets you add additional conditions. 4hen using ,"50-'N5'(%," statements there are %e" points to Deep in mind.

6ts 'LS6$ not 'LS'6$

TUTORIALSPOINT Simply Easy Learning

Page 39

An 6$<T3'N statement can ha!e >ero or one 'LS'2s and it must come a%ter any 'LS'6$2s. An 6$<T3'N statement can ha!e >ero to many 'LS6$2s and they must come 8e%ore the 'LS'. nce an 'LS6$ succeedsG none o% the remaining 'LS6$2s or 'LS'2s "ill 8e tested.

S3nta(/
The synta0 o% an 6$<T3'N<'LS6$ Statement in PL/SQL programming language is5 IE"boolean5e pression <#&1EN 7<* :: E ecutes Q(en t(e boolean e pression < is true EL7IE" boolean5e pression ,# &1EN 7,* :: E ecutes Q(en t(e boolean e pression , is true EL7IE" boolean5e pression =# &1EN 7=* :: E ecutes Q(en t(e boolean e pression = is true EL7E 7F* :: e ecutes Q(en t(e none o9 t(e abo+e condition is true END IE*

)(a.p'e/
DECLARE a nu!ber"=# ./ <--* BEGIN IE " a / <- # &1EN db!s5output6put5line"0Ialue o9 EL7IE " a / ,- # &1EN db!s5output6put5line"0Ialue o9 EL7IE " a / =- # &1EN db!s5output6put5line"0Ialue o9 EL7E db!s5output6put5line"0None o9 END IE* db!s5output6put5line"0E act +alue END* /

a is <-0 #* a is ,-0 #* a is =-0 #* t(e +alues is !atc(in)0#* o9 a is. 0BB a #*

4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 None o9 t(e +alues is !atc(in) E act +alue o9 a is. <-%L/78L procedure success9ully co!pleted6

1ase state.ent
S3nta(/

LiDe the ," statementG the C)%' state*ent selects one sequence o% statements to e0ecute. 3o"e!erG to select the sequenceG the C)%' statement uses a selector rather than multiple 1oolean e0pressions. A selector is an e0pression "hose !alue is used to select one o% se!eral alternati!es.

The synta0 %or case statement in PL/SQL is5

TUTORIALSPOINT Simply Easy Learning

Page 4

CA7E selector 31EN 0+alue<0 &1EN 7<* 31EN 0+alue,0 &1EN 7,* 31EN 0+alue=0 &1EN 7=* 666 EL7E 7n* :: de9ault case END CA7E*

F'o= 0&agra./

)(a.p'e/
DECLARE )rade c(ar"<# ./ 0A0* BEGIN CA7E )rade Q(en 0A0 t(en db!s5output6put5line"0E cellent0#* Q(en 0B0 t(en db!s5output6put5line"0Iery )ood0#* Q(en 0C0 t(en db!s5output6put5line"03ell done0#* Q(en 0D0 t(en db!s5output6put5line"0?ou passed0#* Q(en 0E0 t(en db!s5output6put5line"0Better try a)ain0#* else db!s5output6put5line"0No suc( )rade0#* END CA7E* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5

TUTORIALSPOINT Simply Easy Learning

Page 41

E cellent %L/78L procedure success9ully co!pleted6

Sear2*ed 1AS) state.ent


The searched C)%' statement has no selectorG and it2s I-'N clauses contain search conditions that gi!e 1oolean !alues.

S3nta(/
The synta0 %or searched case statement in PL/SQL is5 CA7E 31EN selector / 0+alue<0 &1EN 7<* 31EN selector / 0+alue,0 &1EN 7,* 31EN selector / 0+alue=0 &1EN 7=* 666 EL7E 7n* :: de9ault case END CA7E*

F'o= 0&agra./

)(a.p'e/
DECLARE )rade c(ar"<# ./ 0B0* BEGIN case Q(en )rade / 0A0 t(en db!s5output6put5line"0E cellent0#* Q(en )rade / 0B0 t(en db!s5output6put5line"0Iery )ood0#* Q(en )rade / 0C0 t(en db!s5output6put5line"03ell done0#* Q(en )rade / 0D0 t(en db!s5output6put5line"0?ou passed0#* Q(en )rade / 0E0 t(en db!s5output6put5line"0Better try a)ain0#* else db!s5output6put5line"0No suc( )rade0#* end case*

TUTORIALSPOINT Simply Easy Learning

Page 42

END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 Iery )ood %L/78L procedure success9ully co!pleted6

nested IF9T,)N9)LS)
6t is al"ays legal in PL/SQL programming to nest ,"5'(%' statementsG "hich means you can use one ,"or '(%' ," statement inside another ," or '(%' ," statement:s;.

S3nta(/
IE" boolean5e pression <#&1EN :: e ecutes Q(en t(e boolean e pression < is true IE"boolean5e pression ,# &1EN :: e ecutes Q(en t(e boolean e pression , is true sequence:o9:state!ents* END IE* EL7E :: e ecutes Q(en t(e boolean e pression < is not true else:state!ents* END IE*

)(a.p'e/
DECLARE a nu!ber"=# ./ <--* b nu!ber"=# ./ ,--* BEGIN :: c(ecM t(e boolean condition IE" a / <-- # &1EN :: i9 condition is true t(en c(ecM t(e 9olloQin) IE" b / ,-- # &1EN :: i9 condition is true t(en print t(e 9olloQin) db!s5output6put5line"0Ialue o9 a is <-- and b is ,--0 #* END IE* END IE* db!s5output6put5line"0E act +alue o9 a is . 0 BB a #* db!s5output6put5line"0E act +alue o9 b is . 0 BB b #* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 Ialue o9 a is <-- and b is ,-E act +alue o9 a is . <-E act +alue o9 b is . ,-%L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 43

CHAPTE R

Loo! s
This chapter describes the various loops used under PL/SQL:

here may 8e a situation "hen you need to e0ecute a 8locD o% code se!eral num8er o%

times. 6n general statements are e0ecuted sequentially5 The %irst statement in a %unction is e0ecuted %irstG %ollo"ed 8y the secondG and so on. Programming languages pro!ide complicated e0ecution paths. !arious control structures that allo" %or more

A loop statement allo"s us to e0ecute a statement or group o% statements multiple times and %ollo"ing is the general %rom o% a loop statement in most o% the programming languages5

PL/SQL pro!ides the %ollo"ing types o% loop to handle the looping requirements. ClicD the %ollo"ing linDs to checD their detail.

TUTORIALSPOINT Simply Easy Learning

Page 44

(oop 0Epe

Description 6n this loop structureG sequence o% statements is enclosed 8et"een the L P and 'ND L P statements. At each iterationG the sequence o% statements is e0ecuted and then control resumes at the top o% the loop. P P ?epeats a statement or group o% statements until a gi!en condition is true. 6t tests the condition 8e%ore e0ecuting the loop 8ody. '0ecute a sequence o% statements multiple times and a88re!iates the code that manages the loop !aria8le. Eou can use one or more loop inside any another 8asic loopG "hile or %or loop.

PL/SQL 1asic L

PL/SQL 436L' L PL/SQL $ ? L

Nested loops in PL/SQL

PL/SQL LOOP
S3nta (/

5as&2

1asic loop structure encloses sequence o% statements in 8et"een the ( / and 'ND ( /statements. 4ith each iterationG the sequence o% statements is e0ecuted and then control resumes at the top o% the loop.

The synta0 o% a 8asic loop in PL/SQL programming language is5 L''% 7equence o9 state!ents* END L''%* 3ere sequence o% statement:s; may 8e a single statement or a 8locD o% statements. An 'A6T statement or an 'A6T 43'N statement is required to 8reaD the loop.

)(a.p'e/
DECLARE nu!ber ./ <-* BEGIN L''% db!s5output6put5line" #* ./ H <-* IE > G- &1EN e it* END IE* END L''%* :: a9ter e it2 control resu!es (ere db!s5output6put5line"0A9ter E it is. 0 BB END* /

#*

4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 <,=FGA9ter E it

is. N-

TUTORIALSPOINT Simply Easy Learning

Page 45

%L/78L procedure success9ully co!pleted6 Eou can use the '.,0 I-'N statement instead o% the '.,0 statement5 DECLARE nu!ber ./ <-* BEGIN L''% db!s5output6put5line" #* ./ H <-* e it 31EN > G-* END L''%* :: a9ter e it2 control resu!es (ere db!s5output6put5line"0A9ter E it is. 0 BB END* /

#*

4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 <,=FGA9ter E it is. N-

%L/78L procedure success9ully co!pleted6

PL/SQL -,IL) LOOP


A I-,(' ( / statement in PL/SQL programming language repeatedly e0ecutes a target statement as long as a gi!en condition is true.

S3nta(/
31ILE condition L''% sequence5o95state!ents END L''%*

)(a.p'e/
DECLARE a nu!ber",# ./ <-* BEGIN 31ILE a < ,- L''% db!s5output6put5line"0+alue o9 a. 0 BB a#* a ./ a H <* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 +alue o9 a. <-

TUTORIALSPOINT Simply Easy Learning

Page 46

+alue +alue +alue +alue +alue +alue +alue +alue +alue

o9 o9 o9 o9 o9 o9 o9 o9 o9

a. a. a. a. a. a. a. a. a.

<< <, <= <F <G <N <J <A <K

%L/78L procedure success9ully co!pleted6

PL/SQL FOR LOOP


A" R( / is a repetition control structure that allo"s you to e%%iciently "rite a loop that needs to e0ecute a speci%ic num8er o% times.

S3nta(/
E'R counter IN initial5+alue 66 9inal5+alue L''% sequence5o95state!ents* END L''%* 3ere is the %lo" o% control in a %or loop5

The initial step is e0ecuted %irstG and only once. This step allo"s you to declare and initiali>e
any loop control !aria8les.

Ne0tG the condition i.e. initial_value .. final_value is e!aluated. 6% it is T?7'G the 8ody o% the loop is e0ecuted. 6% it is $ALS'G the 8ody o% the loop does not e0ecute and %lo" o% control 9umps to the ne0t statement 9ust a%ter the %or loop. A%ter the 8ody o% the %or loop e0ecutesG the !alue o% the counter !aria8le in increased or decreased. The condition is no" e!aluated again. 6% it is T?7'G the loop e0ecutes and the process repeats itsel% :8ody o% loopG then increment stepG and then again condition;. A%ter the condition 8ecomes $ALS'G the $ ?<L P terminates.

$ollo"ing are some special characteristics o% PL/SQL %or loop5

The initial_value and final_value o% the loop !aria8le or counter can 8e literalsG !aria8lesG or e0pressions 8ut must e!aluate to num8ers. ther"iseG PL/SQL raises the prede%ined e0ception =AL7'F'?? ?.

The initial_value need not to 8e #I ho"e!erG the loop counter incre*ent 1or decre*ent3
*ust be 1.

PL/SQL allo"s determine the loop range dynamically at run time.

)(a.p'e/
DECLARE a nu!ber",#* BEGIN

TUTORIALSPOINT Simply Easy Learning

Page 47

E'R a in <- 66 ,- L''% db!s5output6put5line"0+alue o9 a. 0 BB a#* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 +alue +alue +alue +alue +alue +alue +alue +alue +alue +alue +alue o9 o9 o9 o9 o9 o9 o9 o9 o9 o9 o9 a. a. a. a. a. a. a. a. a. a. a. <<< <, <= <F <G <N <J <A <K ,-

%L/78L procedure success9ully co!pleted6

Reverse FOR State.ent

LOOP

1y de%aultG iteration proceeds %rom the initial !alue to the %inal !alueG generally up"ard %rom the lo"er 8ound to the higher 8ound. Eou can re!erse this order 8y using the R'F'R%' Dey"ord. 6n such caseG iteration proceeds the other "ay. A%ter each iterationG the loop counter is decremented. 3o"e!erG you must "rite the range 8ounds in ascending :not descending; order. The %ollo"ing program illustrates this5 DECLARE a nu!ber",# * BEGIN E'R a IN REIER7E <- 66 ,- L''% db!s5output6put5line"0+alue o9 a. 0 BB a#* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 +alue +alue +alue +alue +alue +alue +alue +alue +alue +alue +alue o9 o9 o9 o9 o9 o9 o9 o9 o9 o9 o9 a. a. a. a. a. a. a. a. a. a. a. ,<K <A <J <N <G <F <= <, << <-

%L/78L procedure success9ully co!pleted6

TUTORIALSPOINT

Simply Easy Learning

Page 48

Nested 'oops &n PL/SQL


PL/SQL allo"s using one loop inside another loop. $ollo"ing section sho"s %e" e0amples to illustrate the concept. The synta0 %or a nested 8asic L P statement in PL/SQL is as %ollo"s5

L''% 7equence o9 state!ents< L''% 7equence o9 state!ents, END L''%* END L''%* The synta0 %or a nested $ ? L P statement in PL/SQL is as %ollo"s5

E'R counter< IN initial5+alue< 66 9inal5+alue< L''% sequence5o95state!ents< E'R counter, IN initial5+alue, 66 9inal5+alue, L''% sequence5o95state!ents, END L''%* END L''%* The synta0 %or a nested 436L' L P statement in Pascal is as %ollo"s5

31ILE condition< L''% sequence5o95state!ents< 31ILE condition, L''% sequence5o95state!ents, END L''%* END L''%*

)(a.p'e/
The %ollo"ing program uses a nested 8asic loop to %ind the prime num8ers %rom & to #//5 DECLARE i nu!ber"=#* R nu!ber"=#* BEGIN i ./ ,* L''% R./ ,* L''% e it 31EN ""!od"i2 R# / -# or "R / i##* R ./ R H<* END L''%* IE "R / i # &1EN db!s5output6put5line"i BB 0 is pri!e0#* END IE* i ./ i H <* e it 31EN i / G-* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5

TUTORIALSPOINT Simply Easy Learning

Page 49

, is pri!e = is pri!e G is pri!e J is pri!e << is pri!e <= is pri!e <J is pri!e <K is pri!e ,= is pri!e ,K is pri!e =< is pri!e =J is pri!e F< is pri!e F= is pri!e FJ is pri!e %L/78L procedure success9ully co!pleted6

La4e'&ng a PL/SQL Loop


PL/SQL loops can 8e la8eled. The la8el should 8e enclosed 8y dou8le angle 8racDets :SS and TT;and appear at the 8eginning o% the L P statement. The la8el name can also appear at the end o% the L P statement. Eou may use the la8el in the 'A6T statement to e0it %rom the loop. The %ollo"ing program illustrates the concept5 DECLARE i nu!ber"<#* R nu!ber"<#* BEGIN << outer5loop >> E'R i IN <66= L''% << inner5loop >> E'R R IN <66= L''% db!s5output6put5line"0i is. 0BB i BB 0 and R is. 0 BB R#* END loop inner5loop* END loop outer5loop* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 i i i i i i i i i is. is. is. is. is. is. is. is. is. < < < , , , = = = and and and and and and and and and R R R R R R R R R is. is. is. is. is. is. is. is. is. < , = < , = < , =

%L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 5

T*e Loop 1ontro' State.ents


Loop control statements change e0ecution %rom its normal sequence. 4hen e0ecution lea!es a scopeG all automatic o89ects that "ere created in that scope are destroyed. PL/SQL supports the %ollo"ing control statements. La8eling loops also helps in taDing the control outside a loop. ClicD the %ollo"ing linDs to checD their detail. Control %tate*ent 'A6T statement C NT6N7' statement B T statement Description The '0it statement completes the loop and control passes to the statement immediately a%ter 'ND L P Causes the loop to sDip the remainder o% its 8ody and immediately retest its condition prior to reiterating. Trans%ers control to the la8eled statement. Though it is not ad!ised to use B T statement in your program.

)>IT state.ent
The '.,0 statement in PL/SQL programming language has %ollo"ing t"o usages5 4hen the 'A6T statement is encountered inside a loopG the loop is immediately terminated and program control resumes at the ne0t statement %ollo"ing the loop.

6% you are using nested loops :i.e. one loop inside another loop;G the 'A6T statement "ill

stop the e0ecution o% the innermost loop and start e0ecuting the ne0t line o% code a%ter the 8locD.

S3nta(/
The synta0 %or a 'A6T statement in PL/SQL is as %ollo"s5 E$I&*

F'o= 0&agra./

TUTORIALSPOINT Simply Easy Learning

Page 51

)(a.p'e/
DECLARE a nu!ber",# ./ <-* BEGIN :: Q(ile loop e ecution 31ILE a < ,- L''% db!s5output6put5line "0+alue o9 a. 0 BB a#* a ./ a H <* IE a > <G &1EN :: ter!inate t(e loop usin) t(e e it state!ent E$I&* END IE* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 +alue +alue +alue +alue +alue +alue o9 o9 o9 o9 o9 o9 a. a. a. a. a. a. <<< <, <= <F <G

%L/78L procedure success9ully co!pleted6

T*e )>IT State.ent

-,)N

The '.,05I-'N statement allo"s the condition in the 43'N clause to 8e e!aluated. 6% the condition is trueG the loop completes and control passes to the statement immediately a%ter 'ND L P. $ollo"ing are t"o important aspects %or the 'A6T 43'N statement5

7ntil the condition is trueG the 'A6T<43'N statement acts liDe a N7LL statementG e0cept
%or e!aluating the conditionG and does not terminate the loop.

A statement inside the loop must change the !alue o% the condition.

S3nta (/
The synta0 %or an 'A6T 43'N statement in PL/SQL is as %ollo"s5 E$I& 31EN condition* The 'A6T 43'N statement replaces a conditional state*ent like if5t#en used "ith the 'A6T statement.

)(a.p'e/
DECLARE a nu!ber",# ./ <-* BEGIN :: Q(ile loop e ecution 31ILE a < ,- L''%

TUTORIALSPOINT Simply Easy Learning

Page 52

db!s5output6put5line "0+alue o9 a. 0 BB a#* a ./ a H <* :: ter!inate t(e loop usin) t(e e it Q(en state!ent E$I& 31EN a > <G* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 +alue +alue +alue +alue +alue +alue o9 o9 o9 o9 o9 o9 a. a. a. a. a. a. <<< <, <= <F <G

%L/78L procedure success9ully co!pleted6

1ONTINU) state.ent
The C N0,NG' statement causes the loop to sDip the remainder o% its 8ody and immediately retest its condition prior to reiterating. 6n other "ordsG it %orces the ne0t iteration o% the loop to taDe placeG sDipping any code in 8et"een.

S3nta (/
The synta0 %or a C NT6N7' statement is as %ollo"s5 C'N&IN>E*

F'o= 0&agra./

TUTORIALSPOINT Simply Easy Learning

Page 53

)(a.p'e/
DECLARE a nu!ber",# ./ <-* BEGIN :: Q(ile loop e ecution 31ILE a < ,- L''% db!s5output6put5line "0+alue o9 a. 0 BB a#* a ./ a H <* IE a / <G &1EN :: sMip t(e loop usin) t(e C'N&IN>E state!ent a ./ a H <* C'N&IN>E* END IE* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 +alue +alue +alue +alue +alue +alue +alue +alue +alue o9 o9 o9 o9 o9 o9 o9 o9 o9 a. a. a. a. a. a. a. a. a. <<< <, <= <F <N <J <A <K

%L/78L procedure success9ully co!pleted6

?OTO state.ent
A + 0 statement in PL/SQL programming language pro!ides an unconditional 9ump %rom the B T to a la8eled statement in the same su8program. N 0'< 7se o% B T statement is highly discouraged in any programming language 8ecause it maDes di%%icult to trace the control %lo" o% a programG maDing the program hard to understand and hard to modi%y. Any program that uses a B T can 8e re"ritten so that it doesn2t need the B T .

S3nta (/
The synta0 %or a B T G'&' label* 66 66 << label >> state!ent* statement in PL/SQL is as %ollo"s5

TUTORIALSPOINT Simply Easy Learning

Page 54

F'o= 0&agra./

)(a.p'e/
DECLARE a nu!ber",# ./ <-* BEGIN <<loopstart>> :: Q(ile loop e ecution 31ILE a < ,- L''% db!s5output6put5line "0+alue o9 a. 0 BB a#* a ./ a H <* IE a / <G &1EN a ./ a H <* G'&' loopstart* END IE* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 +alue +alue +alue +alue +alue +alue +alue +alue +alue o9 o9 o9 o9 o9 o9 o9 o9 o9 a. a. a. a. a. a. a. a. a. <<< <, <= <F <N <J <A <K

%L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 55

Restr&2t&ons =&t* ?OTO State.ent


B T Statement in PL/SQL impose the %ollo"ing restrictions5 P statementG

A B T statement cannot 8ranch into an 6$ statementG CAS' statementG L or su8<8locD.

A B T statement cannot 8ranch %rom one 6$ statement clause to anotherG or %rom one CAS' statement 43'N clause to another. A B T statement cannot 8ranch %rom an outer 8locD into a su8<8locD :that isG an inner 1'B6N<'ND 8locD;. A B T statement cannot 8ranch out o% a su8program. To end a su8program earlyG either use the ?'T7?N statement or ha!e B T 8ranch to a place right 8e%ore the end o% the su8program. A B T statement cannot 8ranch %rom an e0ception handler 8acD into the current 1'B6N< 'ND 8locD. 3o"e!erG a B T statement can 8ranch %rom an e0ception handler into an enclosing 8locD.

TUTORIALSPOINT Simply Easy Learning

Page 56

1Strin, s
This chapter describes the concepts under strings:

CHAPTER

he string in PL/SQL is actually a sequence o% characters "ith an optional si>e

speci%ication. The characters could 8e numericG lettersG 8lanDG special characters or a com8ination o% all. PL/SQL o%%ers three Dinds o% strings5

"ixed5lengt# strings5 6n such stringsG programmers speci%y the length "hile declaring Fariable5lengt# strings5 6n such stringsG a ma0imum length upto (&G,+,G %or the string C#aracter large obJects 1C( !s35 These are !aria8le<length strings that can 8e up to #&tera8ytes. PL/SQL strings could 8e either !aria8les or literals. A string literal is enclosed "ithin quotation marDs. $or e0ampleG 0&(is is a strin) literal60 'r 0(ello Qorld0 To include a single quote inside a string literalG you need to type t"o single quotes ne0t to one anotherG liDe5 0t(is isn00t Q(at it looMs liMe0 is speci%ied and no padding taDes place. the string. The string is right<padded "ith spaces to the length so speci%ied.

0e2'ar&ng :ar&a4'es

Str&ng

racle data8ase pro!ides numerous string datatypes G liDeG C3A?G NC3A?G =A?C3A?&G N=A?C3A?&G CL 1G and NCL 1. The datatypes pre%i0ed "ith an 2N2 are 2national character set2 datatypesG that store 7nicode character data. 6% you need to declare a !aria8le<length stringG you must pro!ide the ma0imum length o% that string. $or e0ampleG the =A?C3A?& data type. The %ollo"ing e0ample illustrates declaring and using some string !aria8les5 DECLARE na!e +arc(ar,",-#*

co!pany +arc(ar,"=-#*

TUTORIALSPOINT Simply Easy Learning

Page 57

introduction clob* c(oice c(ar"<#* BEGIN na!e ./ 0So(n 7!it(0* co!pany ./ 0In9otec(0* introduction ./ 0 1ello4 I00! So(n 7!it( 9ro! In9otec(60* c(oice ./ 0y0* IE c(oice / 0y0 &1EN db!s5output6put5line"na!e#* db!s5output6put5line"co!pany#* db!s5output6put5line"introduction#* END IE* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 So(n 7!it( In9otec( Corporation 1ello4 I0! So(n 7!it( 9ro! In9otec(6 %L/78L procedure success9ully co!pleted To declare a %i0ed<length stringG use the C3A? datatype. 3ere you do not ha!e to speci%y a ma0imum length %or a %i0ed<length !aria8le. 6% you lea!e o%% the length constraintG racle Data8ase automatically uses a ma0imum length required. So %ollo"ing t"o declarations 8elo" are identical5 red59la) C1AR"<# ./ 0?0* red59la) C1AR ./ 0?0*

PL/SQL Str&ng Fun2t&ons and Operators


PL/SQL o%%ers the concatenation operator :VV; %or 9oining t"o strings. The %ollo"ing ta8le pro!ides the string %unctions pro!ided 8y PL/SQL5 %.N. "unction & /urpose # & ( ) * + , )%C,,1x32 ?eturns the ASC66 !alue o% the character 0. C-R1x32 ?eturns the character "ith the ASC66 !alue o% 0. C NC)01x8 E32 Concatenates the strings 0 and y and return the appended string. ,N,0C)/1x32 Con!erts the initial letter o% each "ord in 0 to uppercase and returns that string. ,N%0R1x8 find_string K8 startL K8 occurrenceL32 Searches %or %indFstring in 0 and returns the position at "hich it occurs. ,N%0R!1x32 ?eturns the location o% a string "ithin another stringG 8ut returns the !alue in 8ytes. ('N+0-1x32 ?eturns the num8er o% characters in 0.

TUTORIALSPOINT Simply Easy Learning

Page 58

. #/ ##

('N+0-!1x32 ?eturns the length o% a character string in 8ytes %or single 8yte character set. ( I'R1x32 Con!erts the letters in 0 to lo"ercase and returns that string. (/)D1x8 widt# K8 pad_stringL3 2 Pads 0 "ith spaces to le%tG to 8ring the total length o% the string up to "idth characters. (0R,M1x K8 tri*_stringL32 Trims characters %rom the le%t o% 0. N)NF(1x8 6alue32 ?eturns !alue i% 0 matches the NaN special !alue :not a num8er;G other"ise 0 is returned. N(%_,N,0C)/1x32 Same as the 6N6TCAP %unction e0cept that it can use a di%%erent sort method as speci%ied 8y NLSS ?T. N(%_( I'R1x3 2 Same as the L 4'? %unction e0cept that it can use a di%%erent sort method as speci%ied 8y NLSS ?T. N(%_G//'R1x32 Same as the 7PP'? %unction e0cept that it can use a di%%erent sort method as speci%ied 8y NLSS ?T. N(%% R01x32 Changes the method o% sorting the characters. Cust 8e speci%ied 8e%ore any NLS %unctionI other"iseG the de%ault sort "ill 8e used. NF(1x8 6alue32 ?eturns !alue i% 0 is nullI other"iseG 0 is returned. NF(21x8 6alue18 6alue232 ?eturns !alue# i% 0 is not nullI i% 0 is nullG !alue& is returned. R'/()C'1x8 searc#_string8 replace_string32 Searches 0 %or searchFstring and replaces it "ith replaceFstring. R/)D1x8 widt# K8 pad_stringL32 Pads 0 to the right. R0R,M1x K8 tri*_stringL32 Trims 0 %rom the right. % GND'.1x3 2 ?eturns a string containing the phonetic representation o% 0. %G!%0R1x8 start K8 lengt#L32 ?eturns a su8string o% 0 that 8egins at the position speci%ied 8y start. An optional length %or the su8string may 8e supplied. %G!%0R!1x32 Same as S71ST? e0cept the parameters are e0pressed in 8ytes instead o% characters %or the single<8yte character systems. 0R,M1Ktri*_c#ar "R M3 x32 Trims characters %rom the le%t and right o% 0. G//'R1x32 Con!erts the letters in 0 to uppercase and returns that string.

#&

#(

#)

#*

#+

#, ##. &/ &# &&

&(

&)

&* &+

TUTORIALSPOINT Simply Easy Learning

Page 59

The %ollo"ing e0amples illustrate some o% the a8o!e mentioned %unctions and their use5

)(a.p'e 1
DECLARE )reetin)s +arc(ar,"<<# ./ 0(ello Qorld0* BEGIN db!s5output6put5line">%%ER")reetin)s##* db!s5output6put5line"L'3ER")reetin)s##* db!s5output6put5line"INI&CA%")reetin)s##*

/; retrie+e t(e 9irst c(aracter in t(e strin) ;/


db!s5output6put5line " 7>B7&R ")reetin)s2 <2 <##*

/; retrie+e t(e last c(aracter in t(e strin) ;/


db!s5output6put5line " 7>B7&R ")reetin)s2 :<2 <##*

/; retrie+e 9i+e c(aracters2 startin) 9ro! t(e se+ent( position6 ;/ /; retrie+e t(e re!ainder o9 t(e strin)2 startin) 9ro! t(e second position6 ;/ /; 9ind t(e location o9 t(e 9irst "e" ;/

db!s5output6put5line " 7>B7&R ")reetin)s2 J2 G##*

db!s5output6put5line " 7>B7&R ")reetin)s2 ,##* db!s5output6put5line " IN7&R ")reetin)s2 0e0##* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 1ELL' 3'RLD (ello Qorld 1ello 3orld ( d 3orld ello 3orld , %L/78L procedure success9ully co!pleted6

)(a.p'e 2
DECLARE )reetin)s +arc(ar,"=-# ./ 06666661ello 3orld666660* BEGIN db!s5output6put5line"R&RI@")reetin)s2060##* db!s5output6put5line"L&RI@")reetin)s2 060##* db!s5output6put5line"&RI@" 060 9ro! )reetin)s##* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5

TUTORIALSPOINT Simply Easy Learning

Page 6

6666661ello 3orld 1ello 3orld66666 1ello 3orld %L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 61

Array s
This chapter describes concepts under #rrays:

11

CHAPTE R

L/SQL programming language pro!ides a data structure called the =A??AEG "hich can

store a %i0ed<si>e sequential collection o% elements o% the same type. A !array is used to store an ordered collection o% dataG 8ut it is o%ten more use%ul to thinD o% an array as a collection o% !aria8les o% the same type. All !arrays consist o% contiguous memory locations. The lo"est address corresponds to the %irst element and the highest address to the last element.

An array is a part o% collection type data and it stands %or !aria8le<si>e arrays. 4e "ill study other collection types in a later chapter 2PL/SQL Collections2. 'ach element in a !array has an inde0 associated "ith it. 6t also has a ma0imum si>e that can 8e changed dynamically.

1reat&ng a :arra3 T3pe


A !array type is created "ith the C?'AT' TEP' statement. Eou must speci%y the ma0imum si>e and the type o% elements stored in the !array. The 8asic synta0 %or creating a =??AE type at the schema le!el is5 CREA&E 'R RE%LACE &?%E +array5type5na!e I7 IARRA?"n# o9 <ele!ent5type> 4hereG

varray_type_name is a !alid attri8ute nameG

TUTORIALSPOINT Simply Easy Learning

Page 62

n is the num8er o% elements :ma0imum; in the !arrayG element_type is the data type o% the elements o% the array.

Ca0imum si>e o% a !array can 8e changed using the ALT'? TEP' statement. $or e0ampleG CREA&E 'r RE%LACE &?%E na!earray A7 IARRA?"=# 'E IARC1AR,"<-#* / &ype created6 The 8asic synta0 %or creating a =??AE type "ithin a PL/SQL 8locD is5 &?%E +array5type5na!e I7 IARRA?"n# o9 <ele!ent5type> $or e0ample5 &?%E na!earray I7 IARRA?"G# 'E IARC1AR,"<-#* &ype )rades I7 IARRA?"G# 'E IN&EGER*

)(a.p'e 1
The %ollo"ing program illustrates using !arrays5 DECLARE type na!esarray I7 IARRA?"G# 'E IARC1AR,"<-#* type )rades I7 IARRA?"G# 'E IN&EGER* na!es na!esarray* !arMs )rades* total inte)er* BEGIN na!es ./ na!esarray"0La+ita02 0%rita!02 0Ayan02 0Ris(a+02 0ATiT0#* !arMs./ )rades"KA2 KJ2 JA2 AJ2 K,#* total ./ na!es6count* db!s5output6put5line"0&otal 0BB total BB 0 7tudents0#* E'R i in < 66 total L''% db!s5output6put5line"07tudent. 0 BB na!es"i# BB 0 @arMs. 0 BB !arMs"i##* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 7tudent. 7tudent. 7tudent. 7tudent. 7tudent. La+ita @arMs. KA %rita! @arMs. KJ Ayan @arMs. JA Ris(a+ @arMs. AJ ATiT @arMs. K,

%L/78L procedure success9ully co!pleted6 Please note5

6n oracle en!ironmentG the starting inde0 %or !arrays is al"ays #.

TUTORIALSPOINT Simply Easy Learning

Page 63

Eou can initiali>e the !array elements using the constructor method o% the !array typeG "hich has the same name as the !array. =arrays are one<dimensional arrays. A !array is automatically N7LL "hen it is declared and must 8e initiali>ed 8e%ore its elements can 8e re%erenced.

)(a.p'e 2

'lements o% a !array could also 8e a P? 4TEP' o% any data8ase ta8le or PTEP' o% any data8ase ta8le %ield. The %ollo"ing e0ample illustrates the concept5 4e "ill use the C7ST C'?S ta8le stored in our data8ase as5 7elect ; 9ro! custo!ers* H::::H::::::::::H:::::H:::::::::::H::::::::::H B ID B NA@E B AGE B ADDRE77 B 7ALAR? B H::::H::::::::::H:::::H:::::::::::H::::::::::H B < B Ra!es( B =, B A(!edabad B ,---6-- B B , B L(ilan B ,G B Del(i B <G--6-- B B = B Maus(iM B ,= B Lota B ,---6-- B B F B C(aitali B ,G B @u!bai B NG--6-- B B G B 1ardiM B ,J B B(opal B AG--6-- B B N B Lo!al B ,, B @% B FG--6-- B H::::H::::::::::H:::::H:::::::::::H::::::::::H $ollo"ing e0ample maDes use o% cursor "hich you "ill study in detail in a separate chapter. DECLARE C>R7'R c5custo!ers is 7ELEC& na!e ER'@ custo!ers* type c5list is +array "N# o9 custo!ers6na!eOtype* na!e5list c5list ./ c5list"#* counter inte)er ./-* BEGIN E'R n IN c5custo!ers L''% counter ./ counter H <* na!e5list6e tend* na!e5list"counter# ./ n6na!e* db!s5output6put5line"0Custo!er"0BBcounter BB0#.0BBna!e5list"counter##* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 Custo!er"<#. Custo!er",#. Custo!er"=#. Custo!er"F#. Custo!er"G#. Custo!er"N#. Ra!es( L(ilan Maus(iM C(aitali 1ardiM Lo!al

%L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 64

Proce).re s
This chapter describes the procedures under PL/SQL:

12

CHAPTE R

subprogra* is a program unit/module that per%orms a particular tasD. These

su8programs are com8ined to %orm larger programs. This is 8asically called the 2Codular design2. A su8program can 8e in!oDed 8y another su8program or programG "hich is called the calling program. A su8program can 8e created5 At schema le!el 6nside a pacDage 6nside a PL/SQL 8locD

A schema le!el su8program is a standalone subprogra*. 6t is created "ith the C?'AT' P? C'D7?' or C?'AT' $7NCT6 N statement. 6t is stored in the data8ase and can 8e deleted "ith the D? P P? C'D7?' or D? P $7NCT6 N statement. A su8program created inside a pacDage is a packaged subprogra*. 6t is stored in the data8ase and can 8e deleted only "hen the pacDage is deleted "ith the D? P PAC@AB' statement. 4e "ill discuss pacDages in the chapter 2PL/SQL < PacDages2. PL/SQL su8programs are named PL/SQL 8locDs that can 8e in!oDed "ith a set o% parameters. PL/SQL pro!ides t"o Dinds o% su8programs5

"unctions5 these su8programs return a single !alueG mainly used to compute and return a !alue. /rocedures5 these su8programs do not return a !alue directlyG mainly used to per%orm an action. This chapter is going to co!er important aspects o% a /(4%H( procedure and "e "ill co!er /(4%H( function in ne0t chapter.

Parts of a Su4progra.

PL/SQL

'ach PL/SQL su8program has a nameG and may ha!e a parameter list. LiDe anonymous PL/SQL 8locDs andG the named 8locDs a su8programs "ill also ha!e %ollo"ing three parts5

TUTORIALSPOINT Simply Easy Learning

Page 65

%.N. /arts & Description Declarati6e /art 6t is an optional part. 3o"e!erG the declarati!e part %or a su8program does not start "ith the D'CLA?' Dey"ord. 6t contains declarations o% typesG cursorsG constantsG !aria8lesG e0ceptionsG and nested su8programs. These items are local to the su8program and cease to e0ist "hen the su8program completes e0ecution. 'xecutable /art This is a mandatory part and contains statements that per%orm the designated action. 'xception5#andling This is again an optional part. 6t contains the code that handles run<time errors.

& (

1reat&ng a Pro2edure
A procedure is created "ith the C?'AT' ? ?'PLAC' P? C'D7?' statement. The simpli%ied synta0 %or the C?'AT' ? ?'PLAC' P? C'D7?' statement is as %ollo"s5 CREA&E C'R RE%LACED %R'CED>RE procedure5na!e C"para!eter5na!e CIN B '>& B IN '>&D type C2 666D#D UI7 B A7V BEGIN < procedure5body > END procedure5na!e* 4hereG

procedure-name speci%ies the name o% the procedure. X ? ?'PLAC'Y option allo"s modi%ying an e0isting procedure. The optional parameter list contains nameG mode and types o% the parameters. 6N represents that !alue "ill 8e passed %rom outside and 7T represents that this parameter "ill 8e used to return a !alue outside o% the procedure. procedure-body contains the e0ecuta8le part. The AS Dey"ord is used instead o% the 6S Dey"ord %or creating a standalone procedure.

)(a.p'e/
The %ollo"ing e0ample creates a simple procedure that displays the string 23ello 4orldQ2 on the screen "hen e0ecuted. CREA&E 'R RE%LACE %R'CED>RE )reetin)s A7 BEGIN db!s5output6put5line"01ello 3orld40#* END* / 4hen a8o!e code is e0ecuted using SQL promptG it "ill produce the %ollo"ing result5 %rocedure created6

TUTORIALSPOINT Simply Easy Learning

Page 66

)(e2ut&ng a Standa'one Pro2edure


A standalone procedure can 8e called in t"o "ays5

7sing the 'A'C7T' Dey"ord Calling the name o% the procedure %rom a PL/SQL 8locD

The a8o!e procedure named 2greetings2 can 8e called "ith the 'A'C7T' Dey"ord as5 E$EC>&E )reetin)s* The a8o!e call "ould display5 1ello 3orld %L/78L procedure success9ully co!pleted6 The procedure can also 8e called %rom another PL/SQL 8locD5 BEGIN )reetin)s* END* / The a8o!e call "ould display5 1ello 3orld %L/78L procedure success9ully co!pleted6

0e'et&ng a Standa'one Pro2edure


A standalone procedure is deleted "ith the D? P P? C'D7?' statement. Synta0 %or deleting a procedure is5 DR'% %R'CED>RE procedure:na!e* So you can drop greetings procedure 8y using the %ollo"ing statement5 BEGIN DR'% %R'CED>RE )reetin)s* END* /

Para.eter @odes &n PL/SQL Su4progra.s


%.N. /ara*eter Mode & Description ,N An 6N parameter lets you pass a !alue to the su8program. ,t is a read5onlE para*eter. 6nside the su8programG an 6N parameter acts liDe a constant. 6t cannot 8e assigned a !alue. Eou can pass a constantG literalG initiali>ed !aria8leG or e0pression as an 6N parameter. Eou can also #

TUTORIALSPOINT Simply Easy Learning

Page 67

initiali>e it to a de%ault !alueI ho"e!erG in that caseG it is omitted %rom the su8program call. ,t is t#e default *ode of para*eter passing. /ara*eters are passed bE reference. G0 An 7T parameter returns a !alue to the calling program. 6nside the su8programG an 7T parameter acts liDe a !aria8le. Eou can change its !alue and re%erence the !alue a%ter assigning it. 0#e actual para*eter *ust be 6ariable and it is passed bE 6alue. ,N G0 An 6N 7T parameter passes an initial !alue to a su8program and returns an updated !alue to the caller. 6t can 8e assigned a !alue and its !alue can 8e read. The actual parameter corresponding to an 6N 7T %ormal parameter must 8e a !aria8leG not a constant or an e0pression. $ormal parameter must 8e assigned a !alue. )ctual para*eter is passed bE 6alue.

&

&

IN A OUT @ode )(a.p'e 1


This program %inds the minimum o% t"o !aluesG here procedure taDes t"o num8ers using 6N mode and returns their minimum using 7T paramters. DECLARE a nu!ber* b nu!ber* c nu!ber* %R'CED>RE 9ind@in" BEGIN IE < y &1EN T./ * EL7E T./ y* END IE* END* IN nu!ber2 y IN nu!ber2 T '>& nu!ber# I7

BEGIN a./ ,=* b./ FG* 9ind@in"a2 b2 c#* db!s5output6put5line"0 @ini!u! o9 ",=2 FG# . 0 BB c#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 @ini!u! o9 ",=2 FG# . ,= %L/78L procedure success9ully co!pleted6

IN A OUT @ode )(a.p'e 2


This procedure computes the square o% !alue o% a passed !alue. This e0ample sho"s ho" "e can use same parameter to accept a !alue and then return another result. DECLARE a nu!ber* %R'CED>RE squareNu!" BEGIN ./ ; *

IN '>& nu!ber# I7

TUTORIALSPOINT Simply Easy Learning

Page 68

END* BEGIN a./ ,=* squareNu!"a#* db!s5output6put5line"0 7quare o9 ",=#. 0 BB a#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 7quare o9 ",=#. G,K %L/78L procedure success9ully co!pleted6

@et*ods for Pass&ng Para.eters


Actual parameters could 8e passed in three "ays5

Positional notation Named notation Ci0ed notation

POSITIONAL NOTATION
6n positional notationG you can call the procedure as5 9ind@in"a2 b2 c2 d#* 6n positional notationG the %irst actual parameter is su8stituted %or the %irst %ormal parameterI the second actual parameter is su8stituted %or the second %ormal parameterG and so on. SoG a is su8stituted %or 0G 8 is su8stituted %or yG c is su8stituted %or > and d is su8stituted %or m.

NA@)0 NOTATION
6n named notationG the actual parameter is associated "ith the %ormal parameter using the arro" sym8ol : RT ;. So the procedure call "ould looD liDe5 9ind@in" />a2 y/>b2 T/>c2 !/>d#*

@I>)0 NOTATION
6n mi0ed notationG you can mi0 8oth notations in procedure callI ho"e!erG the positional notation should precede the named notation. The %ollo"ing call is legal5 9ind@in"a2 b2 c2 !/>d#* 1ut this is not legal5 9ind@in" />a2 b2 c2 d#*

TUTORIALSPOINT

Simply Easy Learning

Page 69

/.nction s
This chapter describes the functions:

13

CHAPTE R

PL/SQL %unction is same as a procedure e0cept that it returns a !alue. There%oreG all

the discussions o% the pre!ious chapter are true %or %unctions too.

1reat&ng a Fun2t&on
A standalone %unction is created using the C?'AT' $7NCT6 N statement. The simpli%ied synta0 %or the C?'AT' ? ?'PLAC' P? C'D7?' statement is as %ollo"s5 CREA&E C'R RE%LACED E>NC&I'N 9unction5na!e C"para!eter5na!e CIN B '>& B IN '>&D type C2 666D#D RE&>RN return5datatype UI7 B A7V BEGIN < 9unction5body > END C9unction5na!eD* 4hereG

function-name speci%ies the name o% the %unction. X ? ?'PLAC'Y option allo"s modi%ying an e0isting %unction. The optional parameter list contains nameG mode and types o% the parameters. 6N represents that !alue "ill 8e passed %rom outside and 7T represents that this parameter "ill 8e used to return a !alue outside o% the procedure. The %unction must contain a return statement. RET R! clause speci%ies that data type you are going to return %rom the %unction. function-body contains the e0ecuta8le part. The AS Dey"ord is used instead o% the 6S Dey"ord %or creating a standalone %unction.

TUTORIALSPOINT Simply Easy Learning

Page 7

)(a.p' e/
The %ollo"ing e0ample illustrates creating and calling a standalone %unction. This %unction returns the total num8er o% C7ST C'?S in the customers ta8le. 4e "ill use the C7ST C'?S ta8le "hich "e had created in PL/SQL =aria8les chapter5 7elect ; 9ro! custo!ers* H::::H::::::::::H:::::H:::::::::::H::::::::::H B ID B NA@E B AGE B ADDRE77 B 7ALAR? B H::::H::::::::::H:::::H:::::::::::H::::::::::H B < B Ra!es( B =, B A(!edabad B ,---6-- B B , B L(ilan B ,G B Del(i B <G--6-- B B = B Maus(iM B ,= B Lota B ,---6-- B B F B C(aitali B ,G B @u!bai B NG--6-- B B G B 1ardiM B ,J B B(opal B AG--6-- B B N B Lo!al B ,, B @% B FG--6-- B H::::H::::::::::H:::::H:::::::::::H::::::::::H CREA&E 'R RE%LACE E>NC&I'N totalCusto!ers RE&>RN nu!ber I7 total nu!ber",# ./ -* BEGIN 7ELEC& count";# into total ER'@ custo!ers* RE&>RN total* END* / 4hen a8o!e code is e0ecuted using SQL promptG it "ill produce the %ollo"ing result5 Eunction created6

1a''&ng Fun2t&on

4hile creating a %unctionG you gi!e a de%inition o% "hat the %unction has to do. To use a %unctionG you "ill ha!e to call that %unction to per%orm the de%ined tasD. 4hen a program calls a %unctionG program control is trans%erred to the called %unction. A called %unction per%orms de%ined tasD and "hen its return statement is e0ecuted or "hen it last end statement is reachedG it returns program control 8acD to the main program. To call a %unction you simply need to pass the required parameters along "ith %unction name and i% %unction returns a !alue then you can store returned !alue. $ollo"ing program calls the %unction totalCustomers %rom an anonymous 8locD5 DECLARE c nu!ber",#* BEGIN c ./ totalCusto!ers"#* db!s5output6put5line"0&otal no6 o9 Custo!ers. 0 BB c#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5

TUTORIALSPOINT Simply Easy Learning

Page 71

&otal no6 o9 Custo!ers. N %L/78L procedure success9ully co!pleted6

)(a.p'e/
The %ollo"ing is one more e0ample "hich demonstrates DeclaringG De%iningG and 6n!oDing a Simple PL/SQL $unction that computes and returns the ma0imum o% t"o !alues. DECLARE a nu!ber* b nu!ber* c nu!ber* E>NC&I'N 9ind@a " RE&>RN nu!ber I7 T nu!ber* BEGIN IE > y &1EN T./ * EL7E P./ y* END IE* RE&>RN T* END* BEGIN a./ ,=* b./ FG* c ./ 9ind@a "a2 b#* db!s5output6put5line"0 @a i!u! o9 ",=2FG#. 0 BB c#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 @a i!u! o9 ",=2FG#. JA %L/78L procedure success9ully co!pleted6

IN nu!ber2 y IN nu!ber#

PL/SQL Re2urs&ve Fun2t&ons


4e ha!e seen that a program or su8program may call another su8program. 4hen a su8program calls itsel%G it is re%erred to as a recursi!e call and the process is Dno"n as recursion. To illustrate the conceptG let us calculate the %actorial o% a num8er. $actorial o% a num8er n is de%ined as5 n4 / n;"n:<#4 / n;"n:<#;"n:,#4 666 / n;"n:<#;"n:,#;"n:=#666 <

TUTORIALSPOINT Simply Easy Learning

Page 72

The %ollo"ing program calculates the %actorial o% a gi!en num8er 8y calling itsel% recursi!ely5 DECLARE nu! nu!ber* 9actorial nu!ber* E>NC&I'N 9act" nu!ber# RE&>RN nu!ber I7 9 nu!ber* BEGIN IE /- &1EN 9 ./ <* EL7E 9 ./ ; 9act" :<#* END IE* RE&>RN 9* END* BEGIN nu!./ N* 9actorial ./ 9act"nu!#* db!s5output6put5line"0 Eactorial 0BB nu! BB 0 is 0 BB 9actorial#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 Eactorial N is J,%L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 73

C.rsor s
This chapter explains cursors under PL/SQL:

1"

CHAPTE R

racle creates a memory areaG Dno"n as conte0t areaG %or processing an SQL

statementG "hich contains all in%ormation needed %or processing the statementG %or e0ampleG num8er o% ro"s processed etc. A cursor is a pointer to this conte0t area. PL/SQL controls the conte0t area through a cursor. A cursor holds the ro"s :one or more; returned 8y a SQL statement. The set o% ro"s the cursor holds is re%erred to as the acti6e set. Eou can name a cursor so that it could 8e re%erred to in a program to %etch and process the ro"s returned 8y the SQL statementG one at a time. There are t"o types o% cursors5 6mplicit cursors '0plicit cursors

I.p'&2&t 1ursors
6mplicit cursors are automatically created 8y racle "hene!er an SQL statement is e0ecutedG "hen there is no e0plicit cursor %or the statement. Programmers cannot control the implicit cursors and the in%ormation in it. 4hene!er a DCL statement :6NS'?TG 7PDAT' and D'L'T'; is issuedG an implicit cursor is associated "ith this statement. $or 6NS'?T operationsG the cursor holds the data that need to 8e inserted. $or 7PDAT' and D'L'T' operationsG the cursor identi%ies the ro"s that "ould 8e a%%ected. 6n PL/SQLG you can re%er to the most recent implicit cursor as the %H( cursorG "hich al"ays has the attri8utes liDe P$ 7NDG P6S P'NG PN T$ 7NDG and P? 4C 7NT. The SQL cursor has additional attri8utesG P17L@F? 4C 7NT and P17L@F'AC'PT6 NSG designed %or use "ith the $ ?ALL statement. The %ollo"ing ta8le pro!ides the description o% the most used attri8utes5 )ttribute Description

P$ 7ND

?eturns T?7' i% an 6NS'?TG 7PDAT'G or D'L'T' statement a%%ected

TUTORIALSPOINT Simply Easy Learning

Page 74

one or more ro"s or a S'L'CT 6NT ro"s. ther"iseG it returns $ALS'. PN T$ 7ND

statement returned one or more

The logical opposite o% P$ 7ND. 6t returns T?7' i% an 6NS'?TG 7PDAT'G or D'L'T' statement a%%ected no ro"sG or a S'L'CT 6NT statement returned no ro"s. ther"iseG it returns $ALS'. Al"ays returns $ALS' %or implicit cursorsG 8ecause racle closes the SQL cursor automatically a%ter e0ecuting its associated SQL statement. ?eturns the num8er o% ro"s a%%ected 8y an 6NS'?TG 7PDAT'G or D'L'T' statementG or returned 8y a S'L'CT 6NT statement.

P6S P'N P? 4C 7NT

Any SQL cursor attri8ute "ill 8e accessed as sNl:attribute_na*e as sho"n 8elo" in the the e0ample.

)(a.p'e/
4e "ill 8e using the C7ST C'?S ta8le "e had created and used in the pre!ious chapters. 7elect ; 9ro! custo!ers* H::::H::::::::::H:::::H:::::::::::H::::::::::H B ID B NA@E B AGE B ADDRE77 B 7ALAR? B H::::H::::::::::H:::::H:::::::::::H::::::::::H B < B Ra!es( B =, B A(!edabad B ,---6-- B B , B L(ilan B ,G B Del(i B <G--6-- B B = B Maus(iM B ,= B Lota B ,---6-- B B F B C(aitali B ,G B @u!bai B NG--6-- B B G B 1ardiM B ,J B B(opal B AG--6-- B B N B Lo!al B ,, B @% B FG--6-- B H::::H::::::::::H:::::H:::::::::::H::::::::::H The %ollo"ing program "ould update the ta8le and increase salary o% each customer 8y *// and use the SQLP? 4C 7NT attri8ute to determine the num8er o% ro"s a%%ected5 DECLARE total5roQs nu!ber",#* BEGIN >%DA&E custo!ers 7E& salary / salary H G--* IE sqlOnot9ound &1EN db!s5output6put5line"0no custo!ers selected0#* EL7IE sqlO9ound &1EN total5roQs ./ sqlOroQcount* db!s5output6put5line" total5roQs BB 0 custo!ers selected 0#* END IE* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 N custo!ers selected %L/78L procedure success9ully co!pleted6 6% you checD the records in customers ta8leG you "ill %ind that the ro"s ha!e 8een updated5

TUTORIALSPOINT Simply Easy Learning

Page 75

7elect ; 9ro! custo!ers* H::::H::::::::::H:::::H:::::::::::H::::::::::H B ID B NA@E B AGE B ADDRE77 B 7ALAR? B H::::H::::::::::H:::::H:::::::::::H::::::::::H B < B Ra!es( B =, B A(!edabad B ,G--6-- B B , B L(ilan B ,G B Del(i B ,---6-- B B = B Maus(iM B ,= B Lota B ,G--6-- B B F B C(aitali B ,G B @u!bai B J---6-- B B G B 1ardiM B ,J B B(opal B K---6-- B B N B Lo!al B ,, B @% B G---6-- B H::::H::::::::::H:::::H:::::::::::H::::::::::H

)(p'&2&t 1ursors
'0plicit cursors are programmer de%ined cursors %or gaining more control o!er the context area. An e0plicit cursor should 8e de%ined in the declaration section o% the PL/SQL 1locD. 6t is created on a S'L'CT Statement "hich returns more than one ro". The synta0 %or creating an e0plicit cursor is C>R7'R cursor5na!e I7 select5state!ent* 4orDing "ith an e0plicit cursor in!ol!es %our steps5

Declaring the cursor %or initiali>ing in the memory pening the cursor %or allocating memory $etching the cursor %or retrie!ing data Closing the cursor to release allocated memory

0e2'ar&ng t*e 1ursor


Declaring the cursor de%ines the cursor "ith a name and the associated S'L'CT statement. $or e0ample5 C>R7'R c5custo!ers I7 7ELEC& id2 na!e2 address ER'@ custo!ers*

Open&ng 1ursor

t*e

pening the cursor allocates memory %or the cursorG and maDes it ready %or %etching the ro"s returned 8y the SQL statement into it. $or e0ampleG "e "ill open a8o!e de%ined cursor as %ollo"s5 '%EN c5custo!ers*

Fet2*&ng t*e 1ursor


$etching the cursor in!ol!es accessing one ro" at a time. $or e0ample "e "ill %etch ro"s %rom the a8o!e opend cursor as %ollo"s5

TUTORIALSPOINT Simply Easy Learning

Page 76

EE&C1 c5custo!ers IN&' c5id2 c5na!e2 c5addr*

1'os&ng t*e 1ursor


Closing the cursor means releasing the allocated memory. $or e0ampleG "e "ill close a8o!e opened cursor as %ollo"s5 CL'7E c5custo!ers*

)(a.p'e/
$ollo"ing is a complete e0ample to illustrate the concepts o% e0plicit curosrs5 DECLARE c5id custo!ers6idOtype* c5na!e custo!ers6na!eOtype* c5addr custo!ers6addressOtype* C>R7'R c5custo!ers is 7ELEC& id2 na!e2 address ER'@ custo!ers* BEGIN '%EN c5custo!ers* L''% EE&C1 c5custo!ers into c5id2 c5na!e2 c5addr* db!s5output6put5line"c5id BB 0 0 BB c5na!e BB 0 0 BB c5addr#* E$I& 31EN c5custo!ersOnot9ound* END L''%* CL'7E c5custo!ers* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 < , = F G N Ra!es( A(!edabad L(ilan Del(i Maus(iM Lota C(aitali @u!bai 1ardiM B(opal Lo!al @%

%L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 77

Recor) s

1&

CHAPTE R

This chapter describes $ecords in Pl/SQL which is a data structure:

PL/SQL record is a data structure that can hold data items o% di%%erent Dinds. ?ecords

consist o% di%%erent %ieldsG similar to a ro" o% a data8ase ta8le. $or e0ampleG you "ant to Deep tracD o% your 8ooDs in a li8rary. Eou might "ant to tracD the %ollo"ing attri8utes a8out each 8ooD liDeG TitleG AuthorG Su89ectG 1ooD 6D. A record containing a %ield %or each o% these items allo"s treating a 1 @ as a logical unit and allo"s you to organi>e and represent its in%ormation in a 8etter "ay. PL/SQL can handle %ollo"ing types o% records5 Ta8le<8ased Cursor<8ased records 7ser<de%ined records

Ta4'e95ased Re2ords
The P? 4TEP' attri8ute cursor5 based records. ena8les a programmer to create table5based and The %ollo"ing e0ample "ould illustrate the concept o% table5based records. 4e "ill 8e using the C7ST C'?S ta8le "e had created and used in the pre!ious chapters5 DECLARE custo!er5rec custo!ersOroQtype* BEGIN 7ELEC& ; into custo!er5rec ER'@ custo!ers 31ERE id / G* db!s5output6put5line"0Custo!er ID. 0 BB custo!er5rec6id#* db!s5output6put5line"0Custo!er Na!e. 0 BB custo!er5rec6na!e#*

db!s5output6put5line"0Custo!er Address. 0 BB custo!er5rec6address#* db!s5output6put5line"0Custo!er 7alary. 0 BB custo!er5rec6salary#*

TUTORIALSPOINT Simply Easy Learning

Page 78

END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 Custo!er Custo!er Custo!er Custo!er ID. G Na!e. 1ardiM Address. B(opal 7alary. K---

%L/78L procedure success9ully co!pleted6

1ursor95ased Re2ords
The %ollo"ing e0ample "ould illustrate the concept o% cursor5based records. 4e "ill 8e using the C7ST C'?S ta8le "e had created and used in the pre!ious chapters5 DECLARE C>R7'R custo!er5cur is 7ELEC& id2 na!e2 address ER'@ custo!ers* custo!er5rec custo!er5curOroQtype* BEGIN '%EN custo!er5cur* L''% EE&C1 custo!er5cur into custo!er5rec* E$I& 31EN custo!er5curOnot9ound* DB@75'>&%>&6put5line"custo!er5rec6id BB 0 0 BB custo!er5rec6na!e#* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 < , = F G N Ra!es( L(ilan Maus(iM C(aitali 1ardiM Lo!al

%L/78L procedure success9ully co!pleted6

User90ef&ned Re2ords
PL/SQL pro!ides a user<de%ined record type that allo"s you to de%ine di%%erent record structures. ?ecords consist o% di%%erent %ields. Suppose you "ant to Deep tracD o% your 8ooDs in a li8rary. Eou might "ant to tracD the %ollo"ing attri8utes a8out each 8ooD5

Title Author Su89ect

TUTORIALSPOINT

Simply Easy Learning

Page 79

1ooD 6D

0ef&n&ng a Re2ord
The record type is de%ined as5 &?%E type5na!e I7 REC'RD " 9ield5na!e< datatype< CN'& N>LLD C./ DEEA>L& E$%RE77I'ND2 9ield5na!e, datatype, CN'& N>LLD C./ DEEA>L& E$%RE77I'ND2 666 9ield5na!eN datatypeN CN'& N>LLD C./ DEEA>L& E$%RE77I'N#* record:na!e type5na!e* 3ere is the "ay you "ould declare the 1ooD record5 DECLARE &?%E booMs I7 REC'RD "title +arc(ar"G-#2 aut(or +arc(ar"G-#2 subRect +arc(ar"<--#2 booM5id nu!ber#* booM< booMs* booM, booMs*

A22ess&ng F&e'ds
To access any %ield o% a recordG "e use the dot :.; operator. The mem8er access operator is coded as a period 8et"een the record !aria8le name and the %ield that "e "ish to access. $ollo"ing is the e0ample to e0plain usage o% record5 DECLARE type booMs is record "title +arc(ar"G-#2 aut(or +arc(ar"G-#2 subRect +arc(ar"<--#2 booM5id nu!ber#* booM< booMs* booM, booMs* BEGIN

:: BooM < speci9ication

booM<6title ./ 0C %ro)ra!!in)0* booM<6aut(or ./ 0Nu(a Ali 0* booM<6subRect ./ 0C %ro)ra!!in) &utorial0* booM<6booM5id ./ NFKGF-J*

:: BooM , speci9ication

booM,6title ./ 0&eleco! Billin)0* booM,6aut(or ./ 0Para Ali0* booM,6subRect ./ 0&eleco! Billin) &utorial0* booM,6booM5id ./ NFKGJ--*

:: %rint booM < record


db!s5output6put5line"0BooM db!s5output6put5line"0BooM db!s5output6put5line"0BooM db!s5output6put5line"0BooM < < < < title . 0BB booM<6title#* aut(or . 0BB booM<6aut(or#* subRect . 0BB booM<6subRect#* booM5id . 0 BB booM<6booM5id#*

TUTORIALSPOINT

Simply Easy Learning

Page 8

db!s5output6put5line"0BooM db!s5output6put5line"0BooM db!s5output6put5line"0BooM db!s5output6put5line"0BooM END* /

:: %rint booM , record

, , , ,

title . 0BB booM,6title#* aut(or . 0BB booM,6aut(or#* subRect . 0BB booM,6subRect#* booM5id . 0BB booM,6booM5id#*

4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 BooM BooM BooM BooM BooM BooM BooM BooM < < < < , , , , title . C %ro)ra!!in) aut(or . Nu(a Ali subRect . C %ro)ra!!in) &utorial booM5id . NFKGF-J title . &eleco! Billin) aut(or . Para Ali subRect . &eleco! Billin) &utorial booM5id . NFKGJ--

%L/78L procedure success9ully co!pleted6

Re2ords as Para.eters

Su4progra.

Eou can pass a record as a su8program parameter in !ery similar "ay as you pass any other !aria8le. Eou "ould access the record %ields in the similar "ay as you ha!e accessed in the a8o!e e0ample5 DECLARE type booMs is record "title +arc(ar"G-#2 aut(or +arc(ar"G-#2 subRect +arc(ar"<--#2 booM5id nu!ber#* booM< booMs* booM, booMs* %R'CED>RE printbooM "booM booMs# I7 BEGIN db!s5output6put5line "0BooM title . 0 BB booM6title#* db!s5output6put5line"0BooM aut(or . 0 BB booM6aut(or#* db!s5output6put5line" 0BooM subRect . 0 BB booM6subRect#* db!s5output6put5line" 0BooM booM5id . 0 BB booM6booM5id#* END* BEGIN

:: BooM < speci9ication

booM<6title ./ 0C %ro)ra!!in)0* booM<6aut(or ./ 0Nu(a Ali 0* booM<6subRect ./ 0C %ro)ra!!in) &utorial0* booM<6booM5id ./ NFKGF-J*

:: BooM , speci9ication

booM,6title ./ 0&eleco! Billin)0* booM,6aut(or ./ 0Para Ali0* booM,6subRect ./ 0&eleco! Billin) &utorial0* booM,6booM5id ./ NFKGJ--*

:: >se procedure to print booM in9o


printbooM"booM<#*

TUTORIALSPOINT

Simply Easy Learning

Page 81

printbooM"booM,#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 BooM BooM BooM BooM BooM BooM BooM BooM title . C %ro)ra!!in) aut(or . Nu(a Ali subRect . C %ro)ra!!in) &utorial booM5id . NFKGF-J title . &eleco! Billin) aut(or . Para Ali subRect . &eleco! Billin) &utorial booM5id . NFKGJ--

%L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 82

Exce!tion s
This chapter describes error conditions under PL/SQL:

1'

CHAPTE R

n error condition during a program e0ecution is called an e0ception in PL/SQL. PL/SQL

supports programmers to catch such conditions using '.C'/0, N 8locD in the program and an appropriate action is taDen against the error condition. There are t"o types o% e0ceptions5 Systen<de%ined e0ceptions 7ser<de%ined e0ceptions

S3nta( for ,and'&ng

)(2ept&on

The Beneral Synta0 %or e0ception handling is as %ollo"s. 3ere you can list do"n as many as e0ceptions you "ant to handle. The de%ault e0ception "ill 8e handled using "#E! ot$ers T#E!5 DECLARE <declarations section> BEGIN <e ecutable co!!and"s#> E$CE%&I'N <e ception (andlin) )oes (ere > 31EN e ception< &1EN e ception<:(andlin):state!ents 31EN e ception, &1EN e ception,:(andlin):state!ents 31EN e ception= &1EN e ception=:(andlin):state!ents 66666666 31EN ot(ers &1EN e ception=:(andlin):state!ents END*

)(a.p'e

Let us "rite some simple code to illustrate the concept. 4e "ill 8e using the C7ST C'?S ta8le "e had created and used in the pre!ious chapters5

TUTORIALSPOINT Simply Easy Learning

Page 83

DECLARE c5id custo!ers6idOtype ./ A* c5na!e custo!ers6na!eOtype* c5addr custo!ers6addressOtype* BEGIN 7ELEC& na!e2 address IN&' c5na!e2 c5addr ER'@ custo!ers 31ERE id / c5id* DB@75'>&%>&6%>&5LINE "0Na!e. 0BB c5na!e#* DB@75'>&%>&6%>&5LINE "0Address. 0 BB c5addr#* E$CE%&I'N 31EN no5data59ound &1EN db!s5output6put5line"0No suc( custo!er40#* 31EN ot(ers &1EN db!s5output6put5line"0Error40#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 No suc( custo!er4 %L/78L procedure success9ully co!pleted6 The a8o!e program displays the name and address o% a customer "hose 6D is gi!en. Since there is no customer "ith 6D !alue - in our data8aseG the program raises the run<time e0ception N _D)0)_" GND "hich is captured in '.C'/0, N 8locD.

Ra&s&ng )(2ept&ons
'0ceptions are raised 8y the data8ase ser!er automatically "hene!er there is any internal data8ase errorsG 8ut e0ceptions can 8e raised e0plicitly 8y the programmer 8y using the command R),%'. $ollo"ing is the simple synta0 o% raising an e0ception5 DECLARE e ception5na!e E$CE%&I'N* BEGIN IE condition &1EN RAI7E e ception5na!e* END IE* E$CE%&I'N 31EN e ception5na!e &1EN state!ent* END* Eou can use a8o!e synta0 in raising racle standard e0ception or any user<de%ined e0ception. Ne0t section "ill gi!e you an e0ample on raising user<de%ined e0ceptionG similar "ay you can raise racle standard e0ceptions as "ell.

User9def&ned )(2ept&ons
PL/SQL allo"s you to de%ine your o"n e0ceptions according to the need o% your program. A user<de%ined e0ception must 8e declared and then raised e0plicitlyG using either a ?A6S' statement or the procedure D1CSFSTANDA?D.?A6S'FAPPL6CAT6 NF'?? ?.

TUTORIALSPOINT Simply Easy Learning

Page 84

The synta0 %or declaring an e0ception is5 DECLARE !y:e ception E$CE%&I'N*

)(a.p'e/
The %ollo"ing e0ample illustrates the concept. This program asDs %or a customer 6DG "hen the user enters an in!alid 6DG the e0ception in!alidFid is raised. DECLARE c5id custo!ers6idOtype ./ Wcc5id* c5na!e custo!ers6na!eOtype* c5addr custo!ers6addressOtype* :: user de9ined e ception e 5in+alid5id E$CE%&I'N* BEGIN IE c5id </ - &1EN RAI7E e 5in+alid5id* EL7E 7ELEC& na!e2 address IN&' ER'@ custo!ers 31ERE id / c5id*

c5na!e2 c5addr

DB@75'>&%>&6%>&5LINE "0Na!e. 0BB c5na!e#* DB@75'>&%>&6%>&5LINE "0Address. 0 BB c5addr#* END IE* E$CE%&I'N 31EN e 5in+alid5id &1EN db!s5output6put5line"0ID !ust be )reater t(an Tero40#* 31EN no5data59ound &1EN db!s5output6put5line"0No suc( custo!er40#* 31EN ot(ers &1EN db!s5output6put5line"0Error40#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 Enter +alue 9or cc5id. :N "let0s enter a +alue :N# old ,. c5id custo!ers6idOtype ./ Wcc5id* neQ ,. c5id custo!ers6idOtype ./ :N* ID !ust be )reater t(an Tero4 %L/78L procedure success9ully co!pleted6

Pre9def&ned )(2ept&ons
PL/SQL pro!ides many pre<de%ined e0ceptions "hich are e0ecuted "hen any data8ase rule is !iolated 8y a program. $or e0ampleG the prede%ined e0ception N FDATAF$ 7ND is raised "hen a S'L'CT 6NT statement returns no ro"s. The %ollo"ing ta8le lists %e" o% the important pre<de%ined e0ceptions5 'xception racle 'rror %H(C D' Description

TUTORIALSPOINT

Simply Easy Learning

Page 85

ACC'SSF6NT FN7LL

/+*(/

<+*(/

6t is raised "hen a null o89ect is automatically assigned a !alue. 6t is raised "hen none o% the choices in the 43'N clauses o% a CAS' statement is selectedG and there is no 'LS' clause. 6t is raised "hen a program attempts to apply collection methods other than 'A6STS to an uninitiali>ed nested ta8le or !arrayG or the program attempts to assign !alues to the elements o% an uninitiali>ed nested ta8le or !array. 6t is raised "hen duplicate !alues are attempted to 8e stored in a column "ith unique inde0. 6t is raised "hen attempts are made to maDe a cursor operation that is not allo"edG such as closing an unopened cursor. 6t is raised "hen the con!ersion o% a character string into a num8er %ails 8ecause the string does not represent a !alid num8er. 6t is raised "hen s program attempts to log on to the data8ase "ith an in!alid username or pass"ord. 6t is raised "hen a S'L'CT 6NT returns no ro"s. statement

CAS'FN TF$ 7ND

/+*.&

<+*.&

C LL'CT6 NF6SFN7LL

/+*(#

<+*(#

D7PF=ALF NF6ND'A

////#

<#

6N=AL6DFC7?S ?

/#//#

<#//#

6N=AL6DFN7C1'?

/#,&&

<#,&&

L B6NFD'N6'D

/#/#,

<#/#,

N FDATAF$ 7ND

/#)/(

K#//

N TFL BB'DF N

/#/#&

<#/#&

6t is raised "hen a data8ase call is issued "ithout 8eing connected to the data8ase. 6t is raised "hen PL/SQL has an internal pro8lem. 6t is raised "hen a cursor %etches !alue in a !aria8le ha!ing incompati8le data type. 6t is raised "hen a mem8er method is in!oDedG 8ut the instance o% the o89ect type "as not initiali>ed.

P? B?ACF'?? ?

/+*/#

<+*/#

? 4TEP'FC6SCATC3

/+*/)

<+*/)

S'L$F6SFN7LL

(/+&*

<(/+&*

TUTORIALSPOINT Simply Easy Learning

Page 86

ST ?AB'F'?? ?

/+*//

<+*//

6t is raised "hen PL/SQL ran out o% memory or memory "as corrupted. 6t is raised "hen s S'L'CT 6NT returns more than one ro". statement

FCANEF? 4S

/#)&&

<#)&&

=AL7'F'?? ?

/+*/&

<+*/&

6t is raised "hen an arithmeticG con!ersionG truncationG or si>e<constraint error occurs. 6t is raised "hen an attempt is made to di!ide a num8er 8y >ero.

M'? FD6=6D'

/#),+

#),+

TUTORIALSPOINT Simply Easy Learning

Page 87

Tri,,er s
This chapter describes Triggers under PL/SQL:

1(

CHAPTE R

riggers are stored programsG "hich are automatically e0ecuted or %ired "hen some

e!ents occur. Triggers are in %actG "ritten to 8e e0ecuted in response to any o% the %ollo"ing e!ents5 A data8ase manipulation :DCL; statement :D'L'T'G 6NS'?TG or 7PDAT';. A data8ase de%inition :DDL; statement :C?'AT'G ALT'?G or D? P;. A data8ase operation :S'?='?'?? ?G L B NG L B $$G STA?T7PG or S37TD 4N;.

Triggers could 8e de%ined on the ta8leG !ie"G schemaG or data8ase "ith "hich the e!ent is associated.

5enef&ts Tr&ggers
Triggers can purposes5 8e "ritten

of
%or the %ollo"ing

Benerating some deri!ed column !alues automatically 'n%orcing re%erential integrity '!ent logging and storing in%ormation on ta8le access Auditing Synchronous replication o% ta8les 6mposing security authori>ations

Pre!enting in!alid transactions

TUTORIALSPOINT Simply Easy Learning

Page 88

1reat&ng Tr&ggers
The Synta0 %or creating a trigger is5 CREA&E C'R RE%LACE D &RIGGER tri))er5na!e UBEE'RE B AE&ER B IN7&EAD 'E V UIN7ER& C'RD B >%DA&E C'RD B DELE&EV C'E col5na!eD 'N table5na!e CREEERENCING 'LD A7 o NE3 A7 nD CE'R EAC1 R'3D 31EN "condition# DECLARE Declaration:state!ents BEGIN E ecutable:state!ents E$CE%&I'N E ception:(andlin):state!ents END* 4hereG

C?'AT' X ? ?'PLAC'Y T?6BB'? triggerFname 5 Creates or replace an e0isting trigger "ith thetrigger_name. Z1'$ ?' V A$T'? V 6NST'AD $[ 5 This speci%ies "hen the trigger "ould 8e e0ecuted. The 6NST'AD $ clause is used %or creating trigger on a !ie". Z6NS'?T X ?Y V 7PDAT' X ?Y V D'L'T'[5 This speci%ies the DCL operation. X $ colFnameY5 This speci%ies the column name that "ould 8e updated. X N ta8leFnameY5 This speci%ies the name o% the ta8le associated "ith the trigger. X?'$'?'NC6NB LD AS o N'4 AS nY5 This allo"s you to re%er ne" and old !alues %or !arious DCL statementsG liDe 6NS'?TG 7PDAT'G and D'L'T'. X$ ? 'AC3 ? 4Y5 This speci%ies a ro" le!el triggerG i.e.G the trigger "ould 8e e0ecuted %or each ro" 8eing a%%ected. ther"ise the trigger "ill e0ecute 9ust once "hen the SQL statement is e0ecutedG "hich is called a ta8le le!el trigger. 43'N :condition;5 This pro!ides a condition %or ro"s %or "hich the trigger "ould %ire. This clause is !alid only %or ro" le!el triggers.

)(a.p'e/
To start "ithG "e "ill 8e using the C7ST C'?S ta8le "e had created and used in the pre!ious chapters5

7elect ; 9ro! custo!ers* H::::H::::::::::H:::::H:::::::::::H::::::::::H B ID B NA@E B AGE B ADDRE77 B 7ALAR? B H::::H::::::::::H:::::H:::::::::::H::::::::::H

TUTORIALSPOINT Simply Easy Learning

Page 89

B < B Ra!es( B =, B A(!edabad B ,---6-- B B , B L(ilan B ,G B Del(i B <G--6-- B B = B Maus(iM B ,= B Lota B ,---6-- B B F B C(aitali B ,G B @u!bai B NG--6-- B B G B 1ardiM B ,J B B(opal B AG--6-- B B N B Lo!al B ,, B @% B FG--6-- B H::::H::::::::::H:::::H:::::::::::H::::::::::H The %ollo"ing program creates a ro" le!el trigger %or the customers ta8le that "ould %ire %or 6NS'?T or 7PDAT' or D'L'T' operations per%ormed on the C7ST C'?S ta8le. This trigger "ill display the salary di%%erence 8et"een the old !alues and ne" !alues5 CREA&E 'R RE%LACE &RIGGER display5salary5c(an)es BEE'RE DELE&E 'R IN7ER& 'R >%DA&E 'N custo!ers E'R EAC1 R'3 31EN "NE36ID > -# DECLARE sal5di99 nu!ber* BEGIN sal5di99 ./ .NE36salary : .'LD6salary* db!s5output6put5line"0'ld salary. 0 BB .'LD6salary#* db!s5output6put5line"0NeQ salary. 0 BB .NE36salary#* db!s5output6put5line"07alary di99erence. 0 BB sal5di99#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces the %ollo"ing result5 &ri))er created6 3ere %ollo"ing t"o points are important and should 8e noted care%ully5 LD and N'4 re%erences are not a!aila8le %or ta8le le!el triggersG rather you can use them %or record le!el triggers. 6% you "ant to query the ta8le in the same triggerG then you should use the A$T'? Dey"ordG 8ecause triggers can query the ta8le or change it again only a%ter the initial changes are applied and the ta8le is 8acD in a consistent state. A8o!e trigger has 8een "ritten in such a "ay that it "ill %ire 8e%ore any D'L'T' or 6NS'?T or 7PDAT' operation on the ta8leG 8ut you can "rite your trigger on a single or multiple operationsG %or e0ample 1'$ ?' D'L'T'G "hich "ill %ire "hene!er a record "ill 8e deleted using D'L'T' operation on the ta8le.

Tr&gger&ng a Tr&gger
Let us per%orm some DCL operations on the C7ST C'?S ta8le. 3ere is one 6NS'?T statement "hich "ill create a ne" record in the ta8le5 IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "J2 0Lriti02 ,,2 01%02 JG--6-- #* 4hen a record is created in C7ST C'?S ta8leG trigger displayFsalaryFchanges "ill 8e %ired and it "ill display %ollo"ing result5 'ld salary. a8o!e create

TUTORIALSPOINT Simply Easy Learning

Page 9

NeQ salary. JG-7alary di99erence. 1ecause this is a ne" record so old salary is not a!aila8le and a8o!e result is coming as null. No"G let us per%orm one more DCL operation on the C7ST C'?S ta8le. 3ere is one 7PDAT' statement "hich "ill update an e0isting record in the ta8le5 >%DA&E custo!ers 7E& salary / salary H G-31ERE id / ,* 4hen a record is updated in C7ST C'?S ta8leG trigger displayFsalaryFchanges "ill 8e %ired and it "ill display %ollo"ing result5 'ld salary. <G-NeQ salary. ,--7alary di99erence. G-a8o!e create

TUTORIALSPOINT Simply Easy Learning

Page 91

1*
CHAPTER

Pac0a,e s
This chapter describes Pac"ages under PL/SQL:

L/SQL pacDages are schema o89ects that groups logically related PL/SQL typesG

!aria8les and su8programs. A pacDage "ill ha!e t"o mandatory parts5 PacDage speci%ication PacDage 8ody or de%inition

Pa2Bage Spe2&f&2at&on
The speci%ication is the inter%ace to the pacDage. 6t 9ust D'CLA?'S the typesG !aria8lesG constantsG e0ceptionsG cursorsG and su8programs that can 8e re%erenced %rom outside the pacDage. 6n other "ordsG it contains all in%ormation a8out the content o% the pacDageG 8ut e0cludes the code %or the su8programs. All o89ects placed in the speci%ication are called pu8lic o89ects. Any su8program not in the pacDage speci%ication 8ut coded in the pacDage 8ody is called a pri!ate o89ect. The %ollo"ing code snippet sho"s a pacDage speci%ication ha!ing a single procedure. Eou can ha!e many glo8al !aria8les de%ined and multiple procedures or %unctions inside a pacDage. CREA&E %ACLAGE cust5sal A7 %R'CED>RE 9ind5sal"c5id custo!ers6idOtype#* END cust5sal* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 %acMa)e created6

TUTORIALSPOINT Simply Easy Learning

Page 92

Pa2Bage 5od3
The pacDage 8ody has the codes %or !arious methods declared in the pacDage speci%ication and other pri!ate declarationsG "hich are hidden %rom code outside the pacDage. The C?'AT' PAC@AB' 1 DE Statement is used %or creating the pacDage 8ody. The %ollo"ing code snippet sho"s the pacDage 8ody declaration %or the cust_sal pacDage created a8o!e. 6 assumed that "e already ha!e C7ST C'?S ta8le created in our data8ase as mentioned in PL/SQL < =aria8leschapter. CREA&E 'R RE%LACE %ACLAGE B'D? cust5sal A7 %R'CED>RE 9ind5sal"c5id custo!ers6idO&?%E# I7 c5sal custo!ers6salaryO&?%E* BEGIN 7ELEC& salary IN&' c5sal ER'@ custo!ers 31ERE id / c5id* db!s5output6put5line"07alary. 0BB c5sal#* END 9ind5sal* END cust5sal* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 %acMa)e body created6

Us&ng t*e Pa2Bage )'e.ents


The pacDage elements : !aria8lesG procedures or %unctions; are accessed "ith the %ollo"ing synta05 pacMa)e5na!e6ele!ent5na!e* ConsiderG "e already ha!e created a8o!e pacDage in our data8ase schemaG the %ollo"ing program uses the %indFsal method o% the custFsal pacDage5 DECLARE code custo!ers6idOtype ./ Wcc5id* BEGIN cust5sal69ind5sal"code#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it prompt to enter customer 6D and "hen you enter an 6DG it displays corresponding salary as %ollo"s5 Enter +alue 9or cc5id. < 7alary. =--%L/78L procedure success9ully co!pleted6

)(a.p'e/

TUTORIALSPOINT Simply Easy Learning

Page 93

The %ollo"ing program pro!ides a more complete pacDage. 4e "ill use the C7ST C'?S ta8le stored in our data8ase "ith the %ollo"ing records5 7elect ; 9ro! custo!ers* H::::H::::::::::H:::::H:::::::::::H::::::::::H B ID B NA@E B AGE B ADDRE77 B 7ALAR? B H::::H::::::::::H:::::H:::::::::::H::::::::::H B < B Ra!es( B =, B A(!edabad B =---6-- B B , B L(ilan B ,G B Del(i B =---6-- B B = B Maus(iM B ,= B Lota B =---6-- B B F B C(aitali B ,G B @u!bai B JG--6-- B B G B 1ardiM B ,J B B(opal B KG--6-- B B N B Lo!al B ,, B @% B GG--6-- B H::::H::::::::::H:::::H:::::::::::H::::::::::H

T,) PA1<A?) SP)1IFI1ATION/


CREA&E 'R RE%LACE %ACLAGE c5pacMa)e A7 :: Adds a custo!er %R'CED>RE addCusto!er"c5id custo!ers6idOtype2 c5na!e custo!ers6na!eOtype2 c5a)e custo!ers6a)eOtype2 c5addr custo!ers6addressOtype2 c5sal custo!ers6salaryOtype#* :: Re!o+es a custo!er %R'CED>RE delCusto!er"c5id ::Lists all custo!ers %R'CED>RE listCusto!er* END c5pacMa)e* / 4hen the a8o!e code is e0ecuted at SQL promptG it creates the a8o!e pacDage and displays %ollo"ing result5 %acMa)e created6 custo!ers6idO&?%E#*

1R)ATIN? T,) PA1<A?) 5O0C/


CREA&E 'R RE%LACE %ACLAGE B'D? c5pacMa)e A7 %R'CED>RE addCusto!er"c5id custo!ers6idOtype2 c5na!e custo!ers6na!eOtype2 c5a)e custo!ers6a)eOtype2 c5addr custo!ers6addressOtype2 c5sal custo!ers6salaryOtype# I7 BEGIN IN7ER& IN&' custo!ers "id2na!e2a)e2address2salary# IAL>E7"c5id2 c5na!e2 c5a)e2 c5addr2 c5sal#* END addCusto!er* %R'CED>RE delCusto!er"c5id BEGIN DELE&E ER'@ custo!ers 31ERE id / c5id* END delCusto!er* custo!ers6idOtype# I7

TUTORIALSPOINT Simply Easy Learning

Page 94

%R'CED>RE listCusto!er I7 C>R7'R c5custo!ers is 7ELEC& na!e ER'@ custo!ers* &?%E c5list is &ABLE 'E custo!ers6na!eOtype* na!e5list c5list ./ c5list"#* counter inte)er ./-* BEGIN E'R n IN c5custo!ers L''% counter ./ counter H<* na!e5list6e tend* na!e5list"counter# ./ n6na!e* db!s5output6put5line"0Custo!er"0 BBcounterBB 0#0BBna!e5list"counter##* END L''%* END listCusto!er* END c5pacMa)e* / A8o!e e0ample maDes use o% nested table "hich "e "ill discuss in the ne0t chapter. 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 %acMa)e body created6

USIN? T,) PA1<A?)/


The %ollo"ing program uses the methods declared and de%ined in the pacDage cFpacDage. DECLARE code custo!ers6idOtype./ A* BEGIN c5pacMa)e6addcusto!er"J2 0RaRnis(02 ,G2 0C(ennai02 =G--#* c5pacMa)e6addcusto!er"A2 07ub(a!02 =,2 0Del(i02 JG--#* c5pacMa)e6listcusto!er* c5pacMa)e6delcusto!er"code#* c5pacMa)e6listcusto!er* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5
Custo!er"<#. Custo!er",#. Custo!er"=#. Custo!er"F#. Custo!er"G#. Custo!er"N#. Custo!er"J#. Custo!er"A#. Custo!er"<#. Custo!er",#. Custo!er"=#. Custo!er"F#. Custo!er"G#. Custo!er"N#. Custo!er"J#. Ra!es( L(ilan Maus(iM C(aitali 1ardiM Lo!al RaRnis( 7ub(a! Ra!es( L(ilan Maus(iM C(aitali 1ardiM Lo!al RaRnis(

%L/78L procedure success9ully co!pleted

TUTORIALSPOINT Simply Easy Learning

Page 95

Co%%ectio ns

1+

CHAPTE R

This chapter describes %ollection under PL/SQL:

collection is an ordered group o% elements ha!ing the same data type. 'ach element is

identi%ied 8y a unique su8script that represents its position in the collection. PL/SQL pro!ides three collection types5 6nde0<8y ta8les or Associati!e array Nested ta8le =aria8le<si>e array or =array

racle documentation pro!ides the %ollo"ing characteristics %or each type o% collections5 Collection 0Epe Associati!e array :or inde0<8y ta8le; Nu*ber of 'le*ents %ubscript 0Epe Dense or %parse I#ere Created Can !e bJect 0Epe )ttribute

7n8ounded

String or integer

'ither

nly in PL/SQL 8locD

No

Nested ta8le

7n8ounded

6nteger

Starts denseG can 8ecome sparse

'ither in PL/SQL 8locD or at schema le!el 'ither in PL/SQL 8locD or at schema le!el

Ees

=aria8le< si>e array :=array;

1ounded

6nteger

Al"ays dense

Ees

4e ha!e already discussed !array in the chapter 2PL/SQL arrays2. 6n this chapterG "e "ill discuss PL/SQL ta8les.

TUTORIALSPOINT Simply Easy Learning

Page 96

1oth types o% PL/SQL ta8les i.e.G inde0<8y ta8les and nested ta8les ha!e the same structure and their ro"s are accessed using the su8script notation. 3o"e!erG these t"o types o% ta8les di%%er in one aspectI the nested ta8les can 8e stored in a data8ase column and the inde0<8y ta8les cannot.

Inde(953 Ta4'e
An inde0<8y ta8le :also called an associati!e array; is a set o% Dey<!alue pairs. 'ach Dey is uniqueG and is used to locate the corresponding !alue. The Dey can 8e either an integer or a string. An inde0<8y ta8le is created using the %ollo"ing synta0. 3ere "e are creating an inde0<8y ta8le namedta8leFname "hose Deys "ill 8e o% su8scriptFtype and associated !alues "ill 8e o% elementFtype. &?%E type5na!e I7 &ABLE 'E ele!ent5type CN'& N>LLD INDE$ B? subscript5type* table5na!e type5na!e*

)(a.p'e/
$ollo"ing e0ample ho" to create a ta8le to store integer !alues along "ith names and later it prints the same list o% names. DECLARE &?%E salary I7 &ABLE 'E N>@BER INDE$ B? IARC1AR,",-#* salary5list salary* na!e IARC1AR,",-#* BEGIN :: addin) ele!ents to t(e table salary5list"0RaRnis(0# ./ N,---* salary5list"0@inaMs(i0# ./ JG---* salary5list"0@artin0# ./ <-----* salary5list"0Sa!es0# ./ JA---* :: printin) t(e table na!e ./ salary5list6EIR7&* 31ILE na!e I7 N'& null L''% db!s5output6put5line "07alary o9 0 BB na!e BB 0 is 0 BB &'5C1AR"salary5list"na!e###* na!e ./ salary5list6NE$&"na!e#* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 7alary 7alary 7alary 7alary o9 o9 o9 o9 RaRnis( is N,--@inaMs(i is JG--@artin is <----Sa!es is JA---

%L/78L procedure success9ully co!pleted6

TUTORIALSPOINT

Simply Easy Learning

Page 97

)(a.p' e/
'lements o% an inde0<8y ta8le could also 8e a P? 4TEP' o% any data8ase ta8le or PTEP' o% any data8ase ta8le %ield. The %ollo"ing e0ample illustrates the concept. 4e "ill use the C7ST C'?S ta8le stored in our data8ase as5 7elect ; 9ro! custo!ers* H::::H::::::::::H:::::H:::::::::::H::::::::::H B ID B NA@E B AGE B ADDRE77 B 7ALAR? B H::::H::::::::::H:::::H:::::::::::H::::::::::H B < B Ra!es( B =, B A(!edabad B ,---6-- B B , B L(ilan B ,G B Del(i B <G--6-- B B = B Maus(iM B ,= B Lota B ,---6-- B B F B C(aitali B ,G B @u!bai B NG--6-- B B G B 1ardiM B ,J B B(opal B AG--6-- B B N B Lo!al B ,, B @% B FG--6-- B H::::H::::::::::H:::::H:::::::::::H::::::::::H DECLARE C>R7'R c5custo!ers is select na!e 9ro! custo!ers* &?%E c5list I7 &ABLE o9 custo!ers6na!eOtype INDE$ B? binary5inte)er* na!e5list c5list* counter inte)er ./-* BEGIN E'R n IN c5custo!ers L''% counter ./ counter H<* na!e5list"counter# ./ n6na!e* db!s5output6put5line"0Custo!er"0BBcounterBB 0#.0BBna!e5list"counter##* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 Custo!er"<#. Custo!er",#. Custo!er"=#. Custo!er"F#. Custo!er"G#. Custo!er"N#. Ra!es( L(ilan Maus(iM C(aitali 1ardiM Lo!al

%L/78L procedure success9ully co!pleted

Nested Ta4'es
A nested table is liDe a one<dimensional array "ith an ar8itrary num8er o% elements. 3o"e!erG a nested ta8le di%%ers %rom an array in the %ollo"ing aspects5

An array has a declared num8er o% elementsG 8ut a nested ta8le does not. The si>e o% a nested ta8le can increase dynamically.

TUTORIALSPOINT

Simply Easy Learning

Page 98

An array is al"ays dense i.e.G it al"ays has consecuti!e su8scripts. A nested array is dense initiallyG 8ut it can 8ecome sparse "hen elements are deleted %rom it.

An nested table is created using the %ollo"ing synta05 &?%E type5na!e I7 &ABLE 'E ele!ent5type CN'& N>LLD* table5na!e type5na!e* This declaration is similar to declaration o% an inde0<8y ta8leG 8ut there is no 6ND'A 1E clause. A nested ta8le can 8e stored in a data8ase column and so it could 8e used %or simpli%ying SQL operations "here you 9oin a single<column ta8le "ith a larger ta8le. An associati!e array cannot 8e stored in the data8ase.

)(a.p' e/
The %ollo"ing e0amples illustrate the use o% nested ta8le5 DECLARE &?%E na!es5table I7 &ABLE 'E IARC1AR,"<-#* &?%E )rades I7 &ABLE 'E IN&EGER* na!es na!es5table* !arMs )rades* total inte)er* BEGIN na!es ./ na!es5table"0La+ita02 0%rita!02 0Ayan02 0Ris(a+02 0ATiT0#* !arMs./ )rades"KA2 KJ2 JA2 AJ2 K,#* total ./ na!es6count* db!s5output6put5line"0&otal 0BB total BB 0 7tudents0#* E'R i IN < 66 total L''% db!s5output6put5line"07tudent.0BBna!es"i#BB02 @arMs.0 BB !arMs"i##* end loop* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &otal G 7tudents 7tudent.La+ita2 @arMs.KA 7tudent.%rita!2 @arMs.KJ 7tudent.Ayan2 @arMs.JA 7tudent.Ris(a+2 @arMs.AJ 7tudent.ATiT2 @arMs.K, %L/78L procedure success9ully co!pleted6

)(a.p' e/
'lements o% an nested ta8le ta8le could also 8e a P? 4TEP' o% any data8ase ta8le or PTEP' o% any data8ase ta8le %ield. The %ollo"ing e0ample illustrates the concept. 4e "ill use the C7ST C'?S ta8le stored in our data8ase as5 7elect ; 9ro! custo!ers* H::::H::::::::::H:::::H:::::::::::H::::::::::H

TUTORIALSPOINT Simply Easy Learning

Page 99

B ID B NA@E B AGE B ADDRE77 B 7ALAR? B H::::H::::::::::H:::::H:::::::::::H::::::::::H B < B Ra!es( B =, B A(!edabad B ,---6-- B B , B L(ilan B ,G B Del(i B <G--6-- B B = B Maus(iM B ,= B Lota B ,---6-- B B F B C(aitali B ,G B @u!bai B NG--6-- B B G B 1ardiM B ,J B B(opal B AG--6-- B B N B Lo!al B ,, B @% B FG--6-- B H::::H::::::::::H:::::H:::::::::::H::::::::::H DECLARE C>R7'R c5custo!ers is 7ELEC& na!e ER'@ custo!ers* &?%E c5list I7 &ABLE o9 custo!ers6na!eOtype* na!e5list c5list ./ c5list"#* counter inte)er ./-* BEGIN E'R n IN c5custo!ers L''% counter ./ counter H<* na!e5list6e tend* na!e5list"counter# ./ n6na!e* db!s5output6put5line"0Custo!er"0BBcounterBB0#.0BBna!e5list"counter##* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 Custo!er"<#. Custo!er",#. Custo!er"=#. Custo!er"F#. Custo!er"G#. Custo!er"N#. Ra!es( L(ilan Maus(iM C(aitali 1ardiM Lo!al

%L/78L procedure success9ully co!pleted6

1o''e2t&on @et*ods
PL/SQL pro!ides the 8uilt<in collection methods that maDe collections easier to use. The %ollo"ing ta8le lists the methods and their purpose5 %.N. Met#od Na*e & /urpose

'.,%0%1n3 ?eturns T?7' i% the nth element in a collection e0istsI other"ise returns $ALS'.

&

C GN0 ?eturns the num8er o% elements that a collection currently contains. (,M,0

TUTORIALSPOINT Simply Easy Learning

Page 1

ChecDs the Ca0imum Si>e o% a Collection. ) ",R%0 ?eturns the %irst :smallest; inde0 num8ers in a collection that uses integer su8scripts. ()%0 ?eturns the last :largest; inde0 num8ers in a collection that uses integer su8scripts. /R, R1n3 ?eturns the inde0 num8er that precedes inde0 n in a collection. N'.01n3 ?eturns the inde0 num8er that succeeds inde0 n. '.0'ND Appends one null element to a collection. '.0'ND1n3 Appends n null elements to a collection. '.0'ND1n8i3 Appends n copies o% the ith element to a collection. 0R,M ?emo!es one element %rom the end o% a collection. 0R,M1n3 ?emo!es n elements %rom the end o% a collection. D'('0' ?emo!es all elements %rom a collectionG setting C 7NT to /. D'('0'1n3 ?emo!es the nth element %rom an associati!e array "ith a numeric Dey or a nested ta8le. 6% the associati!e array has a string DeyG the element corresponding to the Dey !alue is deleted. 6% n is nullG D'L'T':n; does nothing. D'('0'1*8n3 ?emo!es all elements in the range m..n %rom an associati!e array or nested ta8le. 6% m is larger than n or i% m or n is nullG D'L'T':mGn; does nothing.

#/

##

#&

#(

#)

#*

1o''e2t&on )(2ept&ons
The %ollo"ing ta8le pro!ides the collection e0ceptions and "hen they are raised5 Collection 'xception C LL'CT6 NF6SFN7LL N FDATAF$ 7ND S71SC?6PTF1'E NDFC 7NT S71SC?6PTF 7TS6D'FL6C6T Raised in %ituations Eou try to operate on an atomically null collection. A su8script designates an element that "as deletedG or a none0istent element o% an associati!e array. A su8script e0ceeds the num8er o% elements in a collection. A su8script is outside the allo"ed range.

TUTORIALSPOINT Simply Easy Learning

Page 1 1

=AL7'F'?? ?

A su8script is null or not con!erti8le to the Dey type. This e0ception might occur i% the Dey is de%ined as a PLSF6NT'B'? rangeG and the su8script is outside this range.

TUTORIALSPOINT Simply Easy Learning

Page 1 2

2CHAPTER

Transactio ns
This chapter describes the Transactions under PL/SQL:

data8ase transaction is an atomic unit o% "orD that may consist o% one or more

related SQL statements. 6t is called atomic 8ecause the data8ase modi%ications 8rought a8out 8y the SQL statements that constitute a transaction can collecti!ely 8e either committed i.e. made permanent to the data8ase or rolled 8acD :undone; %rom the data8ase. A success%ully e0ecuted SQL statement and a committed transaction are not same. '!en i% an SQL statement is e0ecuted success%ullyG unless the transaction containing the statement is committedG it can 8e rolled 8acD and all changes made 8y the statement:s; can 8e undone.

Start&ng an Transa2t&on

)nd&ng

A transaction has a 8eginning and an end. A transaction starts "hen one o% the %ollo"ing e!ents taDe place5 The %irst SQL statement is per%ormed a%ter connecting into the data8ase. At each ne" SQL statement issued a%ter a transaction is completed. A transaction ends "hen one o% the %ollo"ing e!ents taDe place5

A C CC6T or a ? LL1AC@ statement is issued. A DDL statementG liDe C?'AT' TA1L' statementG is issuedI 8ecause in that case C CC6T is automatically per%ormed. A DCL statementG such as a B?ANT statementG is issuedI 8ecause in that case a C CC6T is automatically per%ormed. 7ser disconnects %rom the data8ase. 7ser e0its %rom SQLHPL7S 8y issuing the 'A6T commandG a C CC6T is

automatically per%ormed.

TUTORIALSPOINT Simply Easy Learning

Page 1 3

SQLHPlus terminates a8normallyG a ? LL1AC@ is automatically per%ormed. A DCL statement %ailsI in that case a ? LL1AC@ is automatically per%ormed %or undoing that DCL statement.

1o..&tt&ng a Transa2t&on
A transaction is made permanent 8y issuing the SQL command C CC6T. The general synta0 %or the C CC6T command is5 C'@@I&* $or e0ampleG IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "<2 0Ra!es(02 =,2 0A(!edabad02 ,---6-- #* IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 ",2 0L(ilan02 ,G2 0Del(i02 <G--6-- #* IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "=2 0Maus(iM02 ,=2 0Lota02 ,---6-- #* IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "F2 0C(aitali02 ,G2 0@u!bai02 NG--6-- #* IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "G2 01ardiM02 ,J2 0B(opal02 AG--6-- #* IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "N2 0Lo!al02 ,,2 0@%02 FG--6-- #* C'@@I&*

Ro''&ng 5a2B Transa2t&ons


Changes made to the data8ase "ithout C CC6T could 8e undone using the ? LL1AC@ command. The general synta0 %or the ? LL1AC@ command is5 R'LLBACL C&' 7AIE%'IN& < sa+epoint5na!e>D* 4hen a transaction is a8orted due to some unprecedented situationG liDe system %ailureG the entire transaction since a commit is automatically rolled 8acD. i% you are not using sa!epoint then simply use the %ollo"ing statement to roll8acD all the changes5 R'LLBACL*

Savepo&n ts
Sa!epoints are sort o% marDers that help in splitting a long transaction into smaller units 8y setting some checDpoints. 1y setting sa!epoints "ithin a long transactionG you can roll 8acD to a checDpoint i% required. This is done 8y issuing the SA='P 6NT command. The general synta0 %or the SA='P 6NT command is5 7AIE%'IN& < sa+epoint5na!e >*

TUTORIALSPOINT

Simply Easy Learning

Page 1 4

$or e0ample5 IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "J2 0RaRnis(02 ,J2 01%02 KG--6-- #* IN7ER& IN&' C>7&'@ER7 "ID2NA@E2AGE2ADDRE7727ALAR?# IAL>E7 "A2 0Ridd(i02 ,<2 03B02 FG--6-- #* 7AIE%'IN& sa+<* >%DA&E C>7&'@ER7 7E& 7ALAR? / 7ALAR? H <---* R'LLBACL &' sa+<* >%DA&E C>7&'@ER7 7E& 7ALAR? / 7ALAR? H <--31ERE ID / J* >%DA&E C>7&'@ER7 7E& 7ALAR? / 7ALAR? H <--31ERE ID / A* C'@@I&* 3ere R ((!)C$ 0 sa612 statement roll8acD the changes up to the point "here you had maDed sa!epoint sa61 and a%ter that ne" changes "ill start.

Auto.at&2 Transa2t&on 1ontro'


To e0ecute a C CC6T automatically "hene!er an 6NS'?TG 7PDAT' or D'L'T' command is e0ecutedG you can set the A7T C CC6T en!ironment !aria8le as5 7E& A>&'C'@@I& 'N* Eou can turn<o%% auto commit mode using the %ollo"ing command5 7E& A>&'C'@@I& 'EE*

TUTORIALSPOINT Simply Easy Learning

Page 1 5

ate 1 Time
This chapter describes the Date & Time classes:

21

CHAPTE R

L/SQL pro!ides t"o classes o% date and time related data types5

Datetime data types 6nter!al data types

The Datetime data types are5 DAT' T6C'STACP T6C'STACP 46T3 T6C' M N' T6C'STACP 46T3 L CAL T6C' M N'

The 6nter!al data types are5

6NT'?=AL E'A? T 6NT'?=AL DAE T

C NT3 S'C ND

F&e'd :a'ues for 0atet&.e and Interva' 0ata T3pes


1oth dateti*e and inter6al data types consist o% fields. The !alues o% these %ields determine the !alue o% the datatype. The %ollo"ing ta8le lists the %ields and their possi8le !alues %or datetimes and inter!als.
"ield Na*e Falid Dateti*e Falues Falid ,nter6al Falues

E'A?

<),#& to .... :e0cluding year /;

Any non>ero integer

TUTORIALSPOINT Simply Easy Learning

Page 1 6

C NT3

/# to #& /# to (# :limited 8y the !alues o% C NT3 and E'A?G according to the rules o% the calendar %or the locale; // to &( // to *.

/ to ##

DAE

Any non>ero integer

3 7? C6N7T'

/ to &( / to *.

S'C ND

// to *...:n;G "here .:n; is the precision o% time %ractional seconds The .:n; portion is not applica8le %or DAT'.

/ to *...:n;G "here .:n; is the precision o% inter!al %ractional seconds

T6C'M N'F3 7?

<#& to #) :range accommodates daylight sa!ings time changes; Not applica8le %or DAT' or T6C'STACP.

Not applica8le

T6C'M N'FC6N7T'

// to *. Not applica8le %or DAT' or T6C'STACP.

Not applica8le

T6C'M N'F?'B6 N

Not applica8le %or DAT' or T6C'STACP. Not applica8le %or DAT' or T6C'STACP.

Not applica8le

T6C'M N'FA11?

Not applica8le

T*e 0atet&.e 0ata T3pes and Fun2t&ons


$ollo"ing are the Datetime data types5

D)0' < it stores date and time in%ormation in 8oth character and num8er datatypes. 6t is made o% in%ormation on centuryG yearG monthG dateG hourG minuteG and second. 6t is speci%ied as5 0,M'%0)M/ < it is an e0tension o% the DAT' datatype. 6t stores the yearG monthG and day o% the DAT' datatypeG along "ith hourG minuteG and second !alues. 6t is use%ul %or storing precise time !alues. 0,M'%0)M/ I,0- 0,M' O N' < it is a !ariant o% T6C'STACP that includes a time >one region name or a time >one o%%set in its !alue. The time >one o%%set is the di%%erence :in hours and minutes; 8et"een local time and 7TC. This datatype is use%ul %or collecting and e!aluating date in%ormation across geographic regions.

TUTORIALSPOINT Simply Easy Learning

Page 1 7

0,M'%0)M/ I,0- ( C)( 0,M' O N' < it is another !ariant o% T6C'STACP that includes a time >one o%%set in its !alue.

$ollo"ing ta8le pro!ides the Datetime %unctions :"hereG 0 has datetime !alue;5 %.N "unction Na*e & Description )DD_M N0-%1x8 E32 Adds y months to 0.

&

()%0_D)P1x32 ?eturns the last day o% the month.

M N0-%_!'0I''N1x8 E32 ?eturns the num8er o% months 8et"een 0 and y.

N'.0_D)P1x8 daE32 ?eturns the datetime o% the ne0t day a%ter 0.

N'I_0,M'2 ?eturns the time/day !alue %rom a time >one speci%ied 8y the user. R GND1x K8 unitL32 ?ounds 0I

%P%D)0'132 ?eturns the current datetime.

0RGNC1x K8 unitL32 Truncates 0.

Timestamp %unctions :"hereG 0 has a timestamp !alue;5 %.N "unction Na*e & Description CGRR'N0_0,M'%0)M/132 ?eturns a T6C'STACP 46T3 T6C' M N' containing the current session time along "ith the session time >one. '.0R)C01Q P')R A M N0- A D)P A - GR A M,NG0' A %'C ND R A Q 0,M'O N'_- GR A 0,M'O N'_M,NG0' R A Q 0,M'O N'_R'+, N A R 0,M'O N'_)!!R 3 "R M x3 '0tracts and returns a yearG monthG dayG hourG minuteG secondG or time >one %rom 0I "R M_0O1x8 ti*e_zone32 Con!erts the T6C'STACP 0 and time >one speci%ied 8y timeF>one to a T6C'STACP 46T3 T6C'M N'.

&

TUTORIALSPOINT Simply Easy Learning

Page 1 8

( C)(0,M'%0)M/132 ?eturns a T6C'STACP containing the local time in the session time >one.

%P%0,M'%0)M/132 ?eturns a T6C'STACP 46T3 T6C' M N' containing the current data8ase time along "ith the data8ase time >one.

%P%_'.0R)C0_G0C1x32 Con!erts the T6C'STACP 46T3 T6C'M N' 0 to a T6C'STACP containing the date and time in 7TC.

0 _0,M'%0)M/1x8 Kfor*atL32 Con!erts the string 0 to a T6C'STACP.

0 _0,M'%0)M/_0O1x8 Kfor*atL32 Con!erts the string 0 to a T6C'STACP 46T3 T6C'M N'.

)(a.p'es/
The %ollo"ing code snippets illustrate the use o% the a8o!e %unctions5 7ELEC& 7?7DA&E ER'@ D>AL* utput5 -A/=</,-<, G.,G.=F %@

7ELEC& &'5C1AR"C>RREN&5DA&E2 0DD:@@:???? 11.@I.770# ER'@ D>AL*

utput5 =<:-A:,-<, -G.,N.<F

7ELEC& ADD5@'N&17"7?7DA&E2 G# ER'@ D>AL*


utput5 -</=</,-<= G.,N.=< %@

7ELEC& L'CAL&I@E7&A@% ER'@ D>AL* utput5

TUTORIALSPOINT Simply Easy Learning

Page 1 9

A/=</,-<, G.,N.GG6=FJ--- %@

T*e Interva' 0ata T3pes and Fun2t&ons


$ollo"ing are the 6nter!al data types5 6NT'?=AL E'A? T datetime %ields. C NT3 < it stores a period o% time using the E'A? and C NT3

6NT'?=AL DAE T S'C ND < it stores a period o% time in terms o% daysG hoursG minutesG and seconds.

6nter!al %unctions5 %.N "unction Na*e & Description NGM0 D%,N0'RF)(1x8 inter6al_unit32 Con!erts the num8er 0 to an 6NT'?=AL DAE T NGM0 PM,N0'RF)(1x8 inter6al_unit32 Con!erts the num8er 0 to an 6NT'?=AL E'A? T 0 _D%,N0'RF)(1x32 Con!erts the string 0 to an 6NT'?=AL DAE T 0 _PM,N0'RF)(1x32 Con!erts the string 0 to an 6NT'?=AL E'A? T

S'C ND.

&

C NT3.

S'C ND.

C NT3.

TUTORIALSPOINT Simply Easy Learning

Page 11

22
CHAPTER

B2S O.t!.t
This chapter describes D(!S)*+TP+T: the built'in'pac"age

he D!M%_ G0/G0 is a 8uilt in pacDage that ena8les you to display outputG display

de8ugging in%ormationG and send messages %rom PL/SQL 8locDsG su8programsG pacDagesG and triggers. 4e ha!e already used this pacDage all throughout our tutorial. Let us looD at a small code snippet that "ould display all the user ta8les in the data8ase. Try it in your data8ase to list do"n all the ta8le names5 BEGIN db!s5output6put5line "user BB 0 &ables in t(e database.0#* E'R t IN "7ELEC& table5na!e ER'@ user5tables# L''% db!s5output6put5line"t6table5na!e#* END L''%* END* /

05@SDOUTPUT Su4progra.s
The D1CSF 7TP7T pacDage has the %ollo"ing su8programs5 %. N # %ubprogra* & /urpose D!M%_ G0/G0.D,%)!('2 Disa8les message output D!M%_ G0/G0.'N)!('1buffer_size ,N ,N0'+'R D'")G(0 2SSSS32 'na8les message output. A N7LL !alue o% 8u%%erFsi>e represents unlimited 8u%%er si>e. D!M%_ G0/G0.+'0_(,N' 1line G0 F)RC-)R28 status ?etrie!es a single line o% 8u%%ered in%ormation. G0 ,N0'+'R32

&

TUTORIALSPOINT Simply Easy Learning

Page 111

D!M%_ G0/G0.+'0_(,N'% 1lines G0 C-)R)RR8 nu*lines ,N ?etrie!es an array o% lines %rom the 8u%%er. D!M%_ G0/G0.N'I_(,N'2 Puts an end<o%<line marDer D!M%_ G0/G0./G01ite* ,N F)RC-)R232 Places a partial line in the 8u%%er. D!M%_ G0/G0./G0_(,N'1ite* ,N F)RC-)R232 Places a line in the 8u%%er.

G0 ,N0'+'R32

)(a.p'e/
DECLARE lines db!s5output6c(ararr* nu!5lines nu!ber* BEGIN :: enable t(e bu99er Qit( de9ault siTe ,---db!s5output6enable* db!s5output6put5line"01ello Reader40#* db!s5output6put5line"01ope you (a+e enRoyed t(e tutorials40#* db!s5output6put5line"01a+e a )reat ti!e e plorin) pl/sql40#* nu!5lines ./ =* db!s5output6)et5lines"lines2 nu!5lines#* E'R i IN <66nu!5lines L''% db!s5output6put5line"lines"i##* END L''%* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 1ello Reader4 1ope you (a+e enRoyed t(e tutorials4 1a+e a )reat ti!e e plorin) pl/sql4 %L/78L procedure success9ully co!pleted6

TUTORIALSPOINT Simply Easy Learning

Page 112

O$3ect Oriente)
This chapter describes the *b,ect oriented concept:

23

CHAPTE R

L/SQL allo"s de%ining an o89ect typeG "hich helps in designing o89ect<oriented data8ase

in racle. An o89ect type allo"s you to crate composite types. 7sing o89ects allo" you implementing real "orld o89ects "ith speci%ic structure o% data and methods %or operating it. 89ects ha!e attri8utes and methods. Attri8utes are properties o% an o89ect and are used %or storing an o89ect2s stateI and methods are used %or modeling its 8eha!iors. 89ects are created using the C?'AT' X ? ?'PLAC'Y TEP' statement. 1elo" is an e0ample to create a simple address o89ect consisting o% %e" attri8utes5 CREA&E 'R RE%LACE &?%E address A7 'BSEC& "(ouse5no +arc(ar,"<-#2 street +arc(ar,"=-#2 city +arc(ar,",-#2 state +arc(ar,"<-#2 pincode +arc(ar,"<-# #* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &ype created6 Let2s create one more o89ect custo*er "here "e "ill "rap attributes and *et#ods together to ha!e o89ect oriented %eeling5 CREA&E 'R RE%LACE &?%E custo!er A7 'BSEC& "code nu!ber"G#2 na!e +arc(ar,"=-#2 contact5no +arc(ar,"<,#2 addr address2 !e!ber procedure display #* /

TUTORIALSPOINT Simply Easy Learning

Page 113

4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &ype created6

Instant&at&ng O46e2t

an

De%ining an o89ect type pro!ides a 8lueprint %or the o89ect. To use this o89ectG you need to create instances o% this o89ect. Eou can access the attri8utes and methods o% the o89ect using the instance name and t#e access operator 1.3 as %ollo"s5 DECLARE residence address* BEGIN residence ./ address"0<-=A02 0@6G6Road02 0Saipur02 0RaRast(an020,-<=-<0#* db!s5output6put5line"01ouse No. 0BB residence6(ouse5no#* db!s5output6put5line"07treet. 0BB residence6street#* db!s5output6put5line"0City. 0BB residence6city#* db!s5output6put5line"07tate. 0BB residence6state#* db!s5output6put5line"0%incode. 0BB residence6pincode#* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 1ouse No. <-=A 7treet. @6G6Road City. Saipur 7tate. RaRast(an %incode. ,-<=-< %L/78L procedure success9ully co!pleted6

@e.4er @et*ods
Cem8er *et#ods are used %or manipulating the attributes o% the o89ect. Eou pro!ide the declaration o% a mem8er method "hile declaring the o89ect type. The o89ect 8ody de%ines the code %or the mem8er methods. The o89ect 8ody is created using the C?'AT' TEP' 1 DE statement. Constructors are %unctions that return a ne" o89ect as its !alue. '!ery o89ect has a system de%ined constructor method. The name o% the constructor is same as the o89ect type. $or e0ample5 residence ./ address"0<-=A02 0@6G6Road02 0Saipur02 0RaRast(an020,-<=-<0#* The co*parison *et#ods are used %or comparing o89ects. There are t"o "ays to compare o89ects5

Map *et#od5 The Map *et#od is a %unction implemented in such a "ay that its !alue depends upon the !alue o% the attri8utes. $or e0ampleG %or a customer o89ectG i% the customer code is same %or t"o customersG 8oth customers could 8e the same and one. So the relationship 8et"een these t"o o89ects "ould depend upon the !alue o% code. rder *et#od5 The rder *et#ods implement some internal logic %or comparing t"o o89ects. $or e0ampleG %or a rectangle o89ectG a rectangle is 8igger than another rectangle i% 8oth its sides are 8igger.

TUTORIALS POINT Simply Easy Learning

Page 114

Us&ng @ap .et*od


Let us try to understand a8o!e concepts using the %olloi"ing rectangle o89ect5 CREA&E 'R RE%LACE &?%E rectan)le A7 'BSEC& "len)t( nu!ber2 Qidt( nu!ber2 !e!ber 9unction enlar)e" inc nu!ber# return rectan)le2 !e!ber procedure display2 !ap !e!ber 9unction !easure return nu!ber #* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &ype created6 Creating the type 8ody5 CREA&E 'R RE%LACE &?%E B'D? rectan)le A7 @E@BER E>NC&I'N enlar)e"inc nu!ber# return rectan)le I7 BEGIN return rectan)le"sel96len)t( H inc2 sel96Qidt( H inc#* END enlar)e* @E@BER %R'CED>RE display I7 BEGIN db!s5output6put5line"0Len)t(. 0BB len)t(#* db!s5output6put5line"03idt(. 0BB Qidt(#* END display* @A% @E@BER E>NC&I'N !easure return nu!ber I7 BEGIN return "sqrt"len)t(;len)t( H Qidt(;Qidt(##* END !easure* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &ype body created6 No" using the rectangle o89ect and its mem8er %unctions5 DECLARE r< rectan)le* r, rectan)le* r= rectan)le* inc59actor nu!ber ./ G* BEGIN r< ./ rectan)le"=2 F#* r, ./ rectan)le"G2 J#* r= ./ r<6enlar)e"inc59actor#* r=6display*

TUTORIALS POINT Simply Easy Learning

Page 115

IE "r< > r,# &1EN :: callin) !easure 9unction r<6display* EL7E r,6display* END IE* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 Len)t(. A 3idt(. K Len)t(. G 3idt(. J %L/78L procedure success9ully co!pleted6

Us&ng Order .et*od


No"G the sa*e effect could be ac#ie6ed using an order *et#od. Let us recreate the rectangle o89ect using an order method5 CREA&E 'R RE%LACE &?%E rectan)le A7 'BSEC& "len)t( nu!ber2 Qidt( nu!ber2 !e!ber procedure display2 order !e!ber 9unction !easure"r rectan)le# return nu!ber #* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &ype created6 Creating the type 8ody5 CREA&E 'R RE%LACE &?%E B'D? rectan)le A7 @E@BER %R'CED>RE display I7 BEGIN db!s5output6put5line"0Len)t(. 0BB len)t(#* db!s5output6put5line"03idt(. 0BB Qidt(#* END display* 'RDER @E@BER E>NC&I'N !easure"r rectan)le# return nu!ber I7 BEGIN IE"sqrt"sel96len)t(;sel96len)t( H sel96Qidt(;sel96Qidt(#> sqrt"r6len)t(;r6len)t( H r6Qidt(;r6Qidt(## t(en return"<#* EL7E return":<#* END IE* END !easure* END* /

TUTORIALS POINT Simply Easy Learning

Page 116

4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &ype body created6 7sing the rectangle o89ect and its mem8er %unctions5 DECLARE r< rectan)le* r, rectan)le* BEGIN r< ./ rectan)le",=2 FF#* r, ./ rectan)le"<G2 <J#* r<6display* r,6display* IE "r< > r,# &1EN :: callin) !easure 9unction r<6display* EL7E r,6display* END IE* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 Len)t(. ,= 3idt(. FF Len)t(. <G 3idt(. <J Len)t(. ,= 3idt(. FF %L/78L procedure success9ully co!pleted6

In*er&tan2e O46e2ts/

for

PL/SQL

PL/SQL allo"s creating o89ect %rom e0isting 8ase o89ects. To implement inheritanceG the 8ase o89ects should 8e declared as N T $6NAL. The de%ault is $6NAL. The %ollo"ing programs illustrates inheritance in PL/SQL 89ects. Let us create another o89ect named Ta8leTop "hich is inheriting %rom the ?ectangle o89ect. Creating the 8ase rectangle o89ect5 CREA&E 'R RE%LACE &?%E rectan)le A7 'BSEC& "len)t( nu!ber2 Qidt( nu!ber2 !e!ber 9unction enlar)e" inc nu!ber# return rectan)le2 N'& EINAL !e!ber procedure display# N'& EINAL / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &ype created6 Creating the 8ase type 8ody5

TUTORIALS POINT

Simply Easy Learning

Page 117

CREA&E 'R RE%LACE &?%E B'D? rectan)le A7 @E@BER E>NC&I'N enlar)e"inc nu!ber# return rectan)le I7 BEGIN return rectan)le"sel96len)t( H inc2 sel96Qidt( H inc#* END enlar)e* @E@BER %R'CED>RE display I7 BEGIN db!s5output6put5line"0Len)t(. 0BB len)t(#* db!s5output6put5line"03idt(. 0BB Qidt(#* END display* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &ype body created6 Creating the child o89ect tabletop5 CREA&E 'R RE%LACE &?%E tabletop >NDER rectan)le " !aterial +arc(ar,",-#* 'IERRIDING !e!ber procedure display # / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &ype created6 Creating the type 8ody %or the child o89ect ta8letop5 CREA&E 'R RE%LACE &?%E B'D? tabletop A7 'IERRIDING @E@BER %R'CED>RE display I7 BEGIN db!s5output6put5line"0Len)t(. 0BB len)t(#* db!s5output6put5line"03idt(. 0BB Qidt(#* db!s5output6put5line"0@aterial. 0BB !aterial#* END display* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 &ype body created6 7sing the ta8letop o89ect and its mem8er %unctions5 DECLARE t< tabletop* t, tabletop* BEGIN t<./ tabletop",-2 <-2 03ood0#* t, ./ tabletop"G-2 =-2 07teel0#* t<6display*

TUTORIALS POINT Simply Easy Learning

Page 118

t,6display* END* / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5 Len)t(. ,3idt(. <@aterial. 3ood Len)t(. G3idt(. =@aterial. 7teel %L/78L procedure success9ully co!pleted6

A4stra2t PL/SQL

O46e2ts

&n

The N T 6NSTANT6A1L' clause allo"s you to declare an a8stract o89ect. Eou cannot use an a8stract o89ect as it isI you "ill ha!e to create a su8type or child type o% such o89ects to use its %unctionalities. $or e0ampleG CREA&E 'R RE%LACE &?%E rectan)le A7 'BSEC& "len)t( nu!ber2 Qidt( nu!ber2 N'& IN7&AN&IABLE N'& EINAL @E@BER %R'CED>RE display# N'& IN7&AN&IABLE N'& EINAL / 4hen the a8o!e code is e0ecuted at SQL promptG it produces %ollo"ing result5

&ype created6

TUTORIALS POINT

Simply Easy Learning

Page 119

You might also like