11266 Plsql Tutorial

Embed Size (px)

Citation preview

  • 8/13/2019 11266 Plsql Tutorial

    1/186

    PL/SQL Tutorial

  • 8/13/2019 11266 Plsql Tutorial

    2/186

  • 8/13/2019 11266 Plsql Tutorial

    3/186

    Table ofContents

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

  • 8/13/2019 11266 Plsql Tutorial

    4/186

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

  • 8/13/2019 11266 Plsql Tutorial

    5/186

    PL/SQL Datetime and 6nter!al Types ...................................................... #PL/SQL Large 89ect :L 1; Data Types ................................................. PL/SQL 7sering =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..................................................................................................... )

  • 8/13/2019 11266 Plsql Tutorial

    6/186

    $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 ' 6T 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............................................................................... ++

  • 8/13/2019 11266 Plsql Tutorial

    7/186

    '0ample5.................................................................................................. ++'0ecuting a Standalone Procedure ......................................................... +,Deleting a Standalone Procedure ............................................................ +,

    Parameter odes in PL/SQL Su8programs ............................................ +,6N & 7T ode '0ample # ..................................................................... +-6N & 7T ode '0ample ..................................................................... +-

    ethods %or Passing Parameters............................................................. +P S6T6 NAL N TAT6 N....................................................................... +NA 'D N TAT6 N ............................................................................... +

    6 '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

  • 8/13/2019 11266 Plsql Tutorial

    8/186

    1ene%its o% Triggers.................................................................................. --Creating Triggers ..................................................................................... -'0ample5.................................................................................................. -

    Triggering a Trigger ................................................................................. Pac ages ............................................................................... Pac age Speci%ication ............................................................................. Pac age 1ody.......................................................................................... (7sing the Pac age 'lements................................................................... ('0ample5.................................................................................................. (

    T3' PAC@AB' SP'C6$6CAT6 N5......................................................... )C?'AT6NB T3' PAC@AB' 1 DE5 ...................................................... )7S6NB T3' PAC@AB'5 ......................................................................... *

    Collections ............................................................................. +6nde0

  • 8/13/2019 11266 Plsql Tutorial

    9/186

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

    A8stract 89ects in PL/SQL ................................................................... ##

  • 8/13/2019 11266 Plsql Tutorial

    10/186

    PL/SQLOverv ew

    CHAPTER

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

    T he PL/SQL programming language "as de!eloped 8y racle Corporation in the late# - s as procedural e0tension language %or SQL and the racle relational data8ase.$ollo"ing are nota8le %acts a8out PL/SQL5

    PL/SQL is a completely porta8leG high

  • 8/13/2019 11266 Plsql Tutorial

    11/186

    TUTORIALSPOINTSimply Easy Learning Page 1

  • 8/13/2019 11266 Plsql Tutorial

    12/186

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

    Advantages of

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

    SQL is the standard data8ase language and PL/SQL is strongly integrated "ith SQL. PL/SQLsupports 8oth static and dynamic SQL. Static SQL supports D L operations andtransaction control %rom PL/SQL 8loc . Dynamic SQL is SQL allo"s em8edding DDLstatements in PL/SQL 8loc s.

    PL/SQL allo"s sending an entire 8loc o% statements to the data8ase at one time.This reduces net"or 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 datain a data8ase.

    PL/SQL sa!es time on design and de8ugging 8y strong %eaturesG such as e0ceptionhandlingG encapsulationG data hidingG and o89ect

  • 8/13/2019 11266 Plsql Tutorial

    13/186

    TUTORIALSPOINTSimply Easy Learning Page 2

  • 8/13/2019 11266 Plsql Tutorial

    14/186

    Env ronment

    CHAPTER

    2This chapter describes the environment setup for

    starting with PL/SQl:

    P L/SQL is not a standip them in a

    single directory database and under that you "ill %ind %ollo"ing su8

  • 8/13/2019 11266 Plsql Tutorial

    15/186

    TUTORIALSPOINTSimply Easy Learning Page 3

  • 8/13/2019 11266 Plsql Tutorial

    16/186

    Step 2Eou "ill ha!e %ollo"ing screenG 9ust unchec the chec 8o0 and clic continue 8uttonto proceed.

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

    TUTORIALSPOINTSimply Easy Learning Page 4

  • 8/13/2019 11266 Plsql Tutorial

    17/186

    Step 46 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 clic Next 8utton to proceed5

    TUTORIALSPOINTSimply Easy Learning Page 5

  • 8/13/2019 11266 Plsql Tutorial

    18/186

    Step

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

    Step!Just clic Next 8utton to proceed5

  • 8/13/2019 11266 Plsql Tutorial

    19/186

    TUTORIALSPOINTSimply Easy Learning Page 6

  • 8/13/2019 11266 Plsql Tutorial

    20/186

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

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

    TUTORIALSPOINTSimply Easy Learning Page 7

  • 8/13/2019 11266 Plsql Tutorial

    21/186

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

    TUTORIALSPOINTSimply Easy Learning Page 8

  • 8/13/2019 11266 Plsql Tutorial

    22/186

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

    come out.

    TUTORIALSPOINTSimply Easy Learning Page 9

  • 8/13/2019 11266 Plsql Tutorial

    23/186

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

    TUTORIALSPOINTSimply Easy Learning Page 1

  • 8/13/2019 11266 Plsql Tutorial

    24/186

    F&na' Step6% e!erything has 8een done success%ully then its time to !eri%y your installation. Atyour 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/SQLcommands and scripts5

    TUTORIALSPOINTSimply Easy Learning Page 11

  • 8/13/2019 11266 Plsql Tutorial

    25/186

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

    Type your code in a te0t editorG li e NotepadG NotepadKG or 'ditPlusetc.

    Sa!e the %ile "ith the .sql e0tension in the homedirectory.

    Launch SQLHPlus command prompt %rom the directory "here you created your PL/SQL%ile.

    Type % ileFn a m e at the SQLHPlus command prompt to e0ecute yourprogram.

    6% you are not using a %ile to e0ecute PL/SQL scriptsG then simply copy your PL/SQL code andthen right clic on the 8lac "indo" ha!ing SQL prompt and use paste option to pastecomplete code at the command prompt. $inallyG 9ust press enter to e0ecute the codeG i% it isnot already e0ecuted.

    mailto:@file_namemailto:@file_name
  • 8/13/2019 11266 Plsql Tutorial

    26/186

    TUTORIALSPOINTSimply Easy Learning Page 12

  • 8/13/2019 11266 Plsql Tutorial

    27/186

    Bas cSyntax

    CHAPTER

    3This chapter describes the basic syntax followed:

    P L/SQL is a 8loc

  • 8/13/2019 11266 Plsql Tutorial

    28/186

    TUTORIALSPOINTSimply Easy Learning Page 13

  • 8/13/2019 11266 Plsql Tutorial

    29/186

    END*/

    The end line signals the end o% the PL/SQL 8loc . To run the code %rom SQL command lineGyou may need to type at the 8eginning o% the %irst 8lan 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/SQLIdent&f&ersPL/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 numeralsGdollar signsG underscoresG and num8er signs and should not e0ceed ( characters.

    1y de%aultGidentifiers are not case5sensiti e . So you can use integer or ,N0'+'Rto represent a numeric !alue. Eou cannot use a reser!ed ey"ord as an identi%ier.

    T*e PL/SQL0e'&.&ters

    A delimiter is a sym8ol "ith a special meaning. $ollo"ing is the list o% delimiters inPL/SQL5

    Deli*iter Description

    78 58 98 AdditionG su8traction/negationG multiplicationG di!ision

    : Attri8ute indicator

    ; Character string delimiter

    . Component selector

    83 '0pression or list delimiter

    < 3ost !aria8le indicator

    8 6tem separator

    = Quoted identi%ier delimiter

    > ?elational operator

    ? ?emote access indicator

    Statement terminator

    Assignment operator

    >@ Association operator

    AA Concatenation operator

    99 '0ponentiation operator

    BB8 @@ La8el delimiter :8egin and end;

  • 8/13/2019 11266 Plsql Tutorial

    30/186

    TUTORIALSPOINTSimply Easy Learning Page 14

  • 8/13/2019 11266 Plsql Tutorial

    31/186

    98 9 ulti ?elational operators

    B@8 ;>8 >8 > Di%%erent !ersions o% N T 'Q7AL

    T*e PL/SQLo..ents

    Program comments are e0planatory statements that you can include in the PL/SQL code thatyou "rite and helps anyone reading it2s source code. All programming languages allo" %orsome %orm o% comments.

    The PL/SQL supports single line and multi

  • 8/13/2019 11266 Plsql Tutorial

    32/186

    Simply Easy Learning Page 15

  • 8/13/2019 11266 Plsql Tutorial

    33/186

    Type

    Type 8ody

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

    TUTORIALSPOINTSimply Easy Learning Page 16

  • 8/13/2019 11266 Plsql Tutorial

    34/186

    ataTy!es

    CHAPTER

    "This chapter describes the Data Types usedunder PL/SQL:

    P L/SQL !aria8lesG constants and parameters must ha!e a !alid data types "hich speci%iesa storage %ormatG constraintsG and !alid range o% !alues. This tutorial "ill ta eyou 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

    Scalar Single !alues "ith no internal componentsG such as a N7 1'?G DAT'Gor 1 L'AN.

    Large 89ect :L 1; Pointers to large o89ects that are stored separately %rom other dataitemsG such as te0tG graphic imagesG !ideo clipsG and sound "a!e%orms.

    Composite Data items that ha!e internal components that can 8e accessedindi!idually. $or e0ampleG collections and records.

    ?e%erence Pointers to other data items.

    PL/SQL S a'ar 0ata T pes and Su t pesPL/SQL Scalar Data Types and Su8types come under the %ollo"ing categories5

    Date 0Epe Description

    Numeric Numeric !aluesG on "hich arithmetic operations are per%ormed.

    Character Alphanumeric !alues that represent single characters or strings o% characters.

    1oolean Logical !aluesG on "hich logical operations are per%ormed.

    Datetime Dates and times.

    PL/SQL pro!ides su8types o% data types. $or e0ampleG the data type N7 1'? has a su8typecalled 6NT'B'?. Eou can use su8types in your PL/SQL program to ma e the datatypes compati8le "ith data types in other programs "hile em8edding PL/SQL code inanother programG such as a Ja!a program.

  • 8/13/2019 11266 Plsql Tutorial

    35/186

    TUTORIALSPOINTSimply Easy Learning Page 17

  • 8/13/2019 11266 Plsql Tutorial

    36/186

    PL/SQL Nu.er& 0ata T pes and Su t pes$ollo"ing is the detail o% PL/SQL pre

  • 8/13/2019 11266 Plsql Tutorial

    37/186

    PL/SQL *ara ter 0ata T pes andSu t pes$ollo"ing is the detail o% PL/SQL pree o% ( G,+, 8ytes

    ?A4 =aria8lee o% ( G,+,8ytes

    N=A?C3A? =aria8lee o% ( G,+ 8ytes

    L NB ?A4 =aria8le

  • 8/13/2019 11266 Plsql Tutorial

    38/186

    TUTORIALSPOINTSimply Easy Learning Page 19

  • 8/13/2019 11266 Plsql Tutorial

    39/186

    "ield Na*e Falid Dateti*e Falues Falid ,nter al Falues

    E'A?ero integer

    NT3 # to # to ##

    DAE

    # to (# :limited 8y the!alues o% NT3 andE'A?G according to therules o% the calendar %or the locale;

    Any non>ero integer

    3 7? to ( to (

    6N7T' to * to *

    S'C ND to * . :n;G "here

    :n; is the precision o%time %ractional seconds

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

    T6 'M N'F3 7?

  • 8/13/2019 11266 Plsql Tutorial

    40/186

    Simply Easy Learning Page 2

  • 8/13/2019 11266 Plsql Tutorial

    41/186

    PL/SQL User90ef&ned Su t pes A su8type is a su8set o% another data typeG "hich is called its 8ase type. A su8type hasthe same !alid operations as its 8ase typeG 8ut only a su8set o% its !alid !alues.

    PL/SQL prede%ines se!eral su8types in pac age STANDA?D. $or e0ampleG PL/SQLprede%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 = 2- #*

    Eou can de%ine and use your o"n su8types. The %ollo"ing program illustrates de%ining andusing a user

  • 8/13/2019 11266 Plsql Tutorial

    42/186

    Simply Easy Learning Page 21

  • 8/13/2019 11266 Plsql Tutorial

    43/186

    #ar a$%es

    CHAPTER

    &This chapter describes thevariables used:

    A !aria8le is nothing 8ut a name gi!en to a storage area that our programs canmanipulate. 'ach !aria8le in PL/SQL has a speci%ic data typeG "hich determines the si>e andlayout o% the !aria8le2s memoryI the range o% !alues that can 8e stored "ithin that memory andthe 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 numeralsGdollar signsG underscoresG and num8er signs and should not e0ceed ( characters. 1y de%aultG!aria8le names are not case

  • 8/13/2019 11266 Plsql Tutorial

    44/186

    TUTORIALSPOINTSimply Easy Learning Page 22

  • 8/13/2019 11266 Plsql Tutorial

    45/186

    4hen you pro!ide a si>eG scale or precision limit "ith the data typeG it is called a constraineddeclaration . Constrained declarations require less memory than unconstrained declarationsG$or e0ample5

    sales nu!ber - 2 , #*na!e +arc(ar, , #*address +arc(ar, -- #*

    In&t&a'&;&ng :ar&a 'es &nPL/SQL4hene!er you declare a !aria8leG PL/SQL assigns it a de%ault !alue o% N7LL. 6% you "antto initiali>e a !aria8le "ith a !alue other than the N7LL !alueG you can do so during thedeclarationG using either o% the %ollo"ing5

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

    $or e0ample5

    counter binary5inte)er . - *)reetin)s +arc(ar, ,- # DE A L& 01a+e a Good Day0 *

    Eou can also speci%y that a !aria8le should not ha!e a NG(( !alue using theN 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 ma es use o% !arious typeso% !aria8les5

    DECLAREa inte)er . - *b inte)er . ,- *c inte)er *9 real *

    BEGINc . a H b*db!s5output 6put5line 0 alue o9 c. 0 c #*9 . J-6- / =6- *db!s5output 6put5line 0 alue o9 9. 0 9#*

    END*/

    4hen the a8o!e code is e0ecutedG it produces %ollo"ing result5

    alue o9 c. =-alue o9 9. ,=6==================

    %L/78L procedure success9ully co!pleted6

    :ar&a 'e S ope &n PL/SQLPL/SQL allo"s the nesting o% 1loc s i.e.G each program 8loc may contain another inner 8loc . 6%a !aria8le is declared "ithin an inner 8loc G it is not accessi8le to the outer 8loc . 3o"e!erG i%a

  • 8/13/2019 11266 Plsql Tutorial

    46/186

    TUTORIALSPOINTSimply Easy Learning Page 23

  • 8/13/2019 11266 Plsql Tutorial

    47/186

  • 8/13/2019 11266 Plsql Tutorial

    48/186

    TUTORIALSPOINTSimply Easy Learning Page 24

  • 8/13/2019 11266 Plsql Tutorial

    49/186

    IN7ER& IN&' C 7&'@ER7 ID 2 NA@E2 AGE2 ADDRE772 7ALAR?#AL E7 2 0Ra!es(0 2 =, 2 0A(!edabad0 2 ,---6-- #*

    IN7ER& IN&' C 7&'@ER7 ID 2 NA@E2 AGE2 ADDRE772 7ALAR?#AL E7 , 2 0 (ilan0 2 , 2 0Del(i0 2 --6-- #*

    IN7ER& IN&' C 7&'@ER7 ID 2 NA@E2 AGE2 ADDRE772 7ALAR?#AL E7 =2 0Maus(iM0 2 ,= 2 0 ota0 2 ,---6-- #*

    IN7ER& IN&' C 7&'@ER7 ID 2 NA@E2 AGE2 ADDRE772 7ALAR?#AL E7 F2 0C(aitali0 2 , 2 0@u!bai0 2 --6-- #*

    IN7ER& IN&' C 7&'@ER7 ID 2 NA@E2 AGE2 ADDRE772 7ALAR?#AL E7 2 01ardiM0 2 ,J 2 0B(opal0 2 --6-- #*

    IN7ER& IN&' C 7&'@ER7 ID 2 NA@E2 AGE2 ADDRE772 7ALAR?#AL E7 2 0 o!al0 2 ,, 2 0@%02 F --6-- #*

    The %ollo"ing program assigns !alues %rom the a8o!e ta8le to PL/SQL !aria8les using theS'L'CT 6NT clause o% SQL5

    DECLAREc5id custo!ers 6 id Otype . *c5na!e custo!ers 6na!e Otype *c5addr custo!ers 6 address Otype *c5sal custo!ers 6salary Otype *

    BEGIN7ELEC& na!e 2 address 2 salary IN&' c5na!e 2 c5addr 2 c5sal

    R'@ custo!ers31ERE id c5id *

    db!s5output 6put5line0Custo!er 0 c5na!e 0 9ro! 0 c5addr 0 earns 0 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

    TUTORIALSPOINTSimply Easy Learning Page 25

  • 8/13/2019 11266 Plsql Tutorial

    50/186

    Constants

    CHAPTER

    'This chapter shows the usage ofconstants:

    A constant holds a !alue that once declaredG does not change in the program. Aconstant declaration speci%ies its nameG data typeG and !alueG and allocates storage %or it. Thedeclaration can also impose the N T N7LL constraint.

    0e 'ar&ng aonstant

    A constant is declared using the C NSTANT ey"ord. 6t requires an initial !alue and does notallo" that !alue to 8e changedG $or e0ample5

    %I C'N7&AN& N @BER . =6 F K, F *DECLARE

    :: constant declarationpi constant nu!ber . =6 F K, F *:: ot(er declarationsradius nu!ber 2 , #*dia nu!ber 2 , #*circu!9erence nu!ber J 2 , #*

    area nu!ber - 2 , #*BEGIN:: processin)radius . K6 *dia . radius ; , *circu!9erence . ,6- ; pi ; radius *area . pi ; radius ; radius *:: outputdb!s5output 6put5line 0Radius. 0 radius #*db!s5output 6put5line 0Dia!eter. 0 dia #*db!s5output 6put5line 0Circu!9erence. 0 circu!9erence #*db!s5output 6put5line 0Area. 0 area #*

    END*/

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

    Radius. K6

  • 8/13/2019 11266 Plsql Tutorial

    51/186

    Dia!eter. K

    TUTORIALSPOINTSimply Easy Learning Page 26

  • 8/13/2019 11266 Plsql Tutorial

    52/186

  • 8/13/2019 11266 Plsql Tutorial

    53/186

    TUTORIALSPOINTSimply Easy Learning Page 27

  • 8/13/2019 11266 Plsql Tutorial

    54/186

    O!erators

    CHAPTER

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

    A n operator is a sym8ol that tells the compiler to per%orm speci%ic mathematical orlogical manipulations. PL/SQL language is rich in 8uilt

  • 8/13/2019 11266 Plsql Tutorial

    55/186

    TUTORIALSPOINTSimply Easy Learning Page 28

  • 8/13/2019 11266 Plsql Tutorial

    56/186

    )(a.p'eBEGIN

    db!s5output 6put5line - H #*db!s5output 6put5line - : #*

    db!s5output 6put5line - ; #*db!s5output 6put5line - / #*db!s5output 6put5line - ;; #*

    END*/

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

    -,

    -----

    %L/78L procedure success9ully co!pleted6

    Re'at&ona'Operators?elational operators compare t"o e0pressions or !alues and return a 1oolean result. $ollo"ingta8le sho"s all the relational operators supported 8y PL/SQL. Assume !aria8le A holds #and !aria8le 1 holds then5

    perator Description 'xa*ple

    R Chec s i% the !alue o% t"o operands is equal or notG i% yes thencondition 8ecomes true.:A R 1; is nottrue.

    RChec s i% the !alue o% t"o operands is equal or notG i% !alues are notequal then condition 8ecomes true.UR

    :A R 1; istrue.

    Chec s i% the !alue o% le%t operand is greater than the !alue o% rightoperandG i% yes then condition 8ecomes true.

    Chec s i% the !alue o% le%t operand is less than the !alue o% rightoperandG i% yes then condition 8ecomes true.

    R Chec s i% the !alue o% le%t operand is greater than or equal to the!alue o% right operandG i% yes then condition 8ecomes true.

    R Chec s i% the !alue o% le%t operand is less than or equal to the !alueo% right operandG i% yes then condition 8ecomes true.

    :A 1; is nottrue.

    :A 1; is true.

    :A R 1; is nottrue.

    :A R 1; is

    true.

    )(a.p'eDECLARE

    a nu!ber , # . , *b nu!ber , # . - *

    BEGINI a b # t(en

    db!s5output 6put5line 0Line : a is equal to b0 #*EL7E

    db!s5output 6put5line 0Line : a is not equal to b0 #*END I *

    TUTORIALSPOINT

  • 8/13/2019 11266 Plsql Tutorial

    57/186

    Simply Easy Learning Page 29

  • 8/13/2019 11266 Plsql Tutorial

    58/186

    I a < b # t(endb!s5output 6put5line 0Line , : a is less t(an b0 #*

    EL7Edb!s5output 6put5line 0Line , : a is not less t(an b0 #*

    END I *

    I a > b # &1ENdb!s5output 6put5line 0Line = : a is )reater t(an b0 #*

    EL7Edb!s5output 6put5line 0Line = : a is not )reater t(an b0 #*

    END I *

    :: Lets c(an)e +alue o9 a and ba . *b . ,- *I a < b # &1EN

    db!s5output 6put5line 0Line F : a is eit(er equal or less t(an b0 #*END I *

    I b > a # &1EN

    db!s5output 6put5line 0Line : b is eit(er equal or )reater t(an a0 #*END I *

    I a b # &1ENdb!s5output 6put5line 0Line : a is not equal to b0 #*

    EL7Edb!s5output 6put5line 0Line : a is equal to b0 #*

    END I *

    END*/

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

    Line : a is not equal to bLine , : a is not less t(an bLine = : a is )reater t(an bLine F : a is eit(er equal or less t(an bLine : b is eit(er equal or )reater t(an aLine : a is not equal to b

    %L/78L procedure success9ully co!pleted

    o.par&son OperatorsComparison operators are used %or comparing one e0pression to another. The result isal"ays either T?7'G $ALS'G ? N7LL.

    perator Description 'xa*ple

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

    6% 2Mara Ali2 li e 2M AFi2 returns a1oolean trueG"hereasG 2Nuha Ali2li e 2M AFi2 returns a1oolean %alse.

    1'T4''N The 1'T4''N operator tests "hether a !alue lies in aspeci%ied range. 0 1'T4''N a AND 8 means that 0 R a6% 0 R # thenG 08et"een * and

    TUTORIALSPOINTSimply Easy Learning Page 3

  • 8/13/2019 11266 Plsql Tutorial

    59/186

    and 0 R 8. returns trueG 08et"een * and #returns trueG 8ut 08et"een ## and returns %alse.

    6N The 6N operator tests set mem8ership. 0 6N :set; means that0 is equal to any mem8er o% set.

    6% 0 R 2m2 thenG 0 in:2a2G 282G 2c2; returns8oolean %alse 8ut 0 in:2m2G 2n2G 2o2; returns1oolean true.

    6S N7LLThe 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 isnull2 returns 1oolean%alse.

    LI

  • 8/13/2019 11266 Plsql Tutorial

    60/186

    EL7Edb!s5output 6 put5line 0 alse0 #*

    END I *

    I BE&3EEN AND ,- # &1EN

    db!s5output 6 put5line 0&rue0 #*EL7Edb!s5output 6 put5line 0 alse0 #*

    END I *END*/

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

    &rue&rue

    alse

    %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

    DECLAREletter +arc(ar, # . 0!0 *

    BEGINI letter in 0a0 2 0b0 2 0c0 ## &1EN

    db!s5output 6 put5line 0&rue0 #*EL7E

    db!s5output 6 put5line 0 alse0 #*END I *

    I letter in 0!0 2 0n0 2 0o0 ## &1ENdb!s5output 6put5line 0&rue0 #*

    EL7Edb!s5output 6 put5line 0 alse0 #*

    END I *

    I letter is null # &1ENdb!s5output 6 put5line 0&rue0 #*

    EL7Edb!s5output 6 put5line 0 alse0 #*

    END I *END*/

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

    alse&rue

    alse

    %L/78L procedure success9ully co!pleted6

    TUTORIALSPOINTSimply Easy Learning Page 32

  • 8/13/2019 11266 Plsql Tutorial

    61/186

    Log& a'Operators$ollo"ing ta8le sho"s the Logical operators supported 8y PL/SQL. All these operators "oron 1oolean operands and produces 1oolean results. Assume !aria8le A holds true and!aria8le 1 holds %alse then5

    perator Description 'xa*ple

    and Called logical AND operator. 6% 8oth the operands are true thencondition 8ecomes true.

    or Called logical ? perator. 6% any o% the t"o operands is true thencondition 8ecomes true.

    Called logical N T perator. 7sed to re!erse the logical state o% its

    :A and 1; is%alse.

    :A or 1; is true.

    not :A and 1; isnot operand. 6% a condition is true then Logical N T operator "ill ma eit %alse. true.

    )(a.p'eDECLARE

    a boolean . true *b boolean . 9alse *

    BEGINI a AND b# &1EN

    db!s5output 6 put5line 0Line : Condition is true0 #*END I *I a 'R b# &1EN

    db!s5output 6 put5line 0Line , : Condition is true0 #*END I *I N'& a # &1EN

    db!s5output 6 put5line 0Line = : a is not true0 #*EL7E

    db!s5output 6 put5line 0Line = : a is true0 #*END I *I N'& b# &1EN

    db!s5output 6 put5line 0Line F : b is not true0 #*EL7E

    db!s5output 6 put5line 0Line F : b is true0 #*END I *

    END*/

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

    Line , : Condition is true

    Line = : a is trueLine F : b is not true

    %L/78L procedure success9ully co!pleted6

    PL/SQL OperatorPre eden e

    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 e0ampleGthe multiplication operator has higher precedence than the addition operator5

  • 8/13/2019 11266 Plsql Tutorial

    62/186

    TUTORIALSPOINTSimply Easy Learning Page 33

  • 8/13/2019 11266 Plsql Tutorial

    63/186

    $or e0ample 0 R , K ( H I 3ere 0 is assigned #(G not 8ecause operator H hashigher 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 thelo"est appear at the 8ottom. 4ithin an e0pressionG higher precedence operators "ill 8e

    e!aluated %irst.perator peration

    HH e0ponentiation

    KG < identityG negation

    HG / multiplicationG di!ision

    KG

  • 8/13/2019 11266 Plsql Tutorial

    64/186

    Con) t ons

    CHAPTER

    *This chapter describes the Decision

    !a"ing Structure:

    D ecision ma ing structures require that the programmer speci%y one or more conditionsto 8e e!aluated or tested 8y the programG along "ith a statement or statements to 8e e0ecutedi% 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 ma ing; structure %oundin most o% the programming languages5

    PL/SQL programming language pro!ides %ollo"ing types o% decision ma ing statements.Clic the %ollo"ing lin s to chec their detail.

  • 8/13/2019 11266 Plsql Tutorial

    65/186

    TUTORIALSPOINTSimply Easy Learning Page 35

  • 8/13/2019 11266 Plsql Tutorial

    66/186

    %tate*ent Description

    6$ < T3'N statement

    The ," state*ent associates a condition "ith a sequence o%statements enclosed 8y the ey"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 doesnothing.

    6$

  • 8/13/2019 11266 Plsql Tutorial

    67/186

    Simply Easy Learning Page 36

  • 8/13/2019 11266 Plsql Tutorial

    68/186

    )(a.p'e 1

    Let us try a complete e0ample that "ould illustrate the concept5

    DECLAREa nu!ber , # . - *

    BEGINa . - *

    :: c(ecM t(e boolean condition usin) i9 state!ent

    I a < ,- # &1EN:: i9 condition is true t(en print t(e 9olloQin)db!s5output 6 put5line 0a is less t(an ,- 0 #*

    END I *db!s5output 6put5line 0+alue o9 a is . 0 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 2Consider "e ha!e a ta8le and %e" records in the ta8le as "e had created in P L/ S Q L = a r ia 8 leT ypes

    DECLAREc5id custo!ers 6 id Otype . *c5sal custo!ers 6salary Otype *

    TUTORIALSPOINTSimply Easy Learning Page 37

    http://www.tutorialspoint.com/plsql/plsql_variable_types.htmhttp://www.tutorialspoint.com/plsql/plsql_variable_types.htmhttp://www.tutorialspoint.com/plsql/plsql_variable_types.htmhttp://www.tutorialspoint.com/plsql/plsql_variable_types.htmhttp://www.tutorialspoint.com/plsql/plsql_variable_types.htm
  • 8/13/2019 11266 Plsql Tutorial

    69/186

    BEGIN7ELEC& salaryIN&' c5sal

    R'@ custo!ers31ERE id c5id *

    I c5sal < ,--- # &1EN%DA&Ecusto!ers7E& salary salary H ---

    31ERE id c5id *db!s5output 6 put5line 07alary updated0 #*

    END I *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 an optional sequenceo%'(%' statementsG "hich e0ecutes "hen the condition is ")(%' .

    S nta(

    Synta0 %or the 6$

  • 8/13/2019 11266 Plsql Tutorial

    70/186

    )(a.p'e

    Let us try a complete e0ample that "ould illustrate the concept5

    DECLAREa nu!ber =# . -- *

    BEGIN:: c(ecM t(e boolean condition usin) i9 state!entI a < ,- # &1EN

    :: i9 condition is true t(en print t(e 9olloQin)db!s5output 6 put5line 0a is less t(an ,- 0 #*

    EL7Edb!s5output 6 put5line 0a is not less t(an ,- 0 #*

    END I *db!s5output 6put5line 0+alue o9 a is . 0 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)LSIFstate.entThe ,"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 '(%," clauselets you add additional conditions.4hen using ,"50-'N5'(%," statements there are %e" points to eep inmind.

    6ts 'LS6$ not 'LS'6$

  • 8/13/2019 11266 Plsql Tutorial

    71/186

    TUTORIALSPOINTSimply Easy Learning Page 39

  • 8/13/2019 11266 Plsql Tutorial

    72/186

    An 6$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.

    S nta(

    The synta0 o% an 6$

  • 8/13/2019 11266 Plsql Tutorial

    73/186

    CA7E selector31EN 0+alue 0 &1EN 7 *31EN 0+alue,0 &1EN 7, *31EN 0+alue=0 &1EN 7= *666

    EL7E 7n * :: de9ault caseEND CA7E *

    F'o= 0&agra.

    )(a.p'eDECLARE

    )rade c(ar # . 0A0 *BEGIN

    CA7E )radeQ(en 0A0 t(en db!s5output 6put5line 0E cellent0 #*Q(en 0B0 t(en db!s5output 6put5line 0 ery )ood0 #*Q(en 0C0 t(en db!s5output 6put5line 03ell done0 #*Q(en 0D0 t(en db!s5output 6put5line 0?ou passed0 #*Q(en 0 0 t(en db!s5output 6put5line 0Better try a)ain0 #*else db!s5output 6 put5line 0No suc( )rade0 #*

    END CA7E *END*/

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

    TUTORIALSPOINTSimply Easy Learning Page 41

  • 8/13/2019 11266 Plsql Tutorial

    74/186

    E cellent

    %L/78L procedure success9ully co!pleted6

    Sear *ed AS) state.entThe searched C)%' statement has no selectorG and it2s I-'N clauses containsearch conditions that gi!e 1oolean !alues.

    S nta(

    The synta0 %or searched case statement in PL/SQL is5

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

    END CA7E *

    F'o= 0&agra.

    )(a.p'e

    DECLARE)rade c(ar # . 0B0 *BEGIN

    caseQ(en )rade 0A0 t(en db!s5output 6 put5line 0E cellent0 #*Q(en )rade 0B0 t(en db!s5output 6 put5line 0 ery )ood0 #*Q(en )rade 0C0 t(en db!s5output 6 put5line 03ell done0 #*Q(en )rade 0D0 t(en db!s5output 6 put5line 0?ou passed0 #*Q(en )rade 0 0 t(en db!s5output 6 put5line 0Better try a)ain0 #*else db!s5output 6 put5line 0No suc( )rade0 #*

    end case *

    TUTORIALSPOINTSimply Easy Learning Page 42

  • 8/13/2019 11266 Plsql Tutorial

    75/186

    END*/

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

    ery )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 youcan use one ," or '(%' ," statement inside another ," or '(%' ," statement:s;.

    S nta(I boolean5e pression # &1EN

    :: e ecutes Q(en t(e boolean e pression is true

    I boolean5e pression , # &1EN:: e ecutes Q(en t(e boolean e pression , is truesequence:o9:state!ents *

    END I *EL7E

    :: e ecutes Q(en t(e boolean e pression is not trueelse:state!ents *

    END I *

    )(a.p'eDECLARE

    a nu!ber =# . -- *b nu!ber =# . ,-- *

    BEGIN:: c(ecM t(e boolean conditionI a -- # &1EN:: i9 condition is true t(en c(ecM t(e 9olloQin)

    I b ,-- # &1EN:: i9 condition is true t(en print t(e 9olloQin)

    db!s5output 6 put5line 0 alue o9 a is -- and b is ,--0 #*END I *

    END I *db!s5output 6put5line 0E act +alue o9 a is . 0 a #*db!s5output 6put5line 0E act +alue o9 b is . 0 b #*

    END*/

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

    alue o9 a is -- and b is ,--E act +alue o9 a is . --E act +alue o9 b is . ,--

    %L/78L procedure success9ully co!pleted6

    TUTORIALSPOINTSimply Easy Learning Page 43

  • 8/13/2019 11266 Plsql Tutorial

    76/186

    Loo!s

    CHAPTER

    +This chapter describes the various loops usedunder PL/SQL:

    T here may 8e a situation "hen you need to e0ecute a 8loc o% code se!eral num8er o%times. 6n general statements are e0ecuted sequentially5 The %irst statement in a %unction ise0ecuted %irstG %ollo"ed 8y the secondG and so on.

    Programming languages pro!ide !arious control structures that allo" %or morecomplicated e0ecution paths.

    A loop statement allo"s us to e0ecute a statement or group o% statements multiple timesand %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. Clicthe %ollo"ing lin s to chec their detail.

  • 8/13/2019 11266 Plsql Tutorial

    77/186

    TUTORIALSPOINTSimply Easy Learning Page 44

  • 8/13/2019 11266 Plsql Tutorial

    78/186

    (oop 0Epe Description

    PL/SQL 1asic L P

    6n this loop structureG sequence o% statements is enclosed 8et"eenthe L P and 'ND L P statements. At each iterationG thesequence o% statements is e0ecuted and then control resumes at

    the top o% the loop.

    PL/SQL 436L' L P ?epeats a statement or group o% statements until a gi!en condition istrue. 6t tests the condition 8e%ore e0ecuting the loop 8ody.

    PL/SQL $ ? L P'0ecute a sequence o% statements multiple times and a88re!iatesthe code that manages the loop !aria8le.

    Nested loops in PL/SQL Eou can use one or more loop inside any another 8asic loopG "hile or%or loop.

    PL/SQL 5as&LOOP1asic loop structure encloses sequence o% statements in 8et"een the ( / and'ND ( / statements. 4ith each iterationG the sequence o% statements is e0ecuted and thencontrol resumes at the top o% the loop.

    S nta(The synta0 o% a 8asic loop in PL/SQL programming languageis5

    L''%7equence o9 state!ents *

    END L''% *

    3ere sequence o% statement:s; may 8e a single statement or a 8loc o% statements. An ' 6Tstatement or an ' 6T 43'N statement is required to 8rea the loop.

    )(a.p'eDECLARE

    nu!ber . - *BEGIN

    L''%db!s5output 6 put5line #*

    . H - *I > - &1EN

    e it *END I *

    END L''% *:: a9ter e it2 control resu!es (eredb!s5output 6put5line 0A9ter E it is. 0 #*

    END*/

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

    -,-=-F-

    -A9ter E it is. -

  • 8/13/2019 11266 Plsql Tutorial

    79/186

  • 8/13/2019 11266 Plsql Tutorial

    80/186

    %L/78L procedure success9ully co!pleted6

    Eou can use the ' ,0 I-'N statement instead o% the ' ,0 statement5

    DECLAREnu!ber . - *

    BEGINL''%

    db!s5output 6 put5line #*. H - *

    e it 31EN > - *END L''% *:: a9ter e it2 control resu!es (eredb!s5output 6put5line 0A9ter E it is. 0 #*

    END*/

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

    -,-

    =-

    F-

    -

    A9ter E it is. -

    %L/78L procedure success9ully co!pleted6

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

    S nta(31ILE condition L''%

    sequence5o95state!entsEND L''% *

    )(a.p'eDECLARE

    a nu!ber , # . - *BEGIN

    31ILE a < ,- L''%db!s5output 6 put5line 0+alue o9 a. 0 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. -

    TUTORIALSPOINTSimply Easy Learning Page 46

  • 8/13/2019 11266 Plsql Tutorial

    81/186

    +alue o9 a. +alue o9 a. ,+alue o9 a. =+alue o9 a. F+alue o9 a.

    +alue o9 a. +alue o9 a. J+alue o9 a. +alue o9 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 thatneeds to e0ecute a speci%ic num8er o% times.

    S nta('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>eany 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 increasedor decreased.

    The condition is no" e!aluated again. 6% it is T?7'G the loop e0ecutes and the processrepeats itsel% :8ody o% loopG then increment stepG and then again condition;. A%terthe condition 8ecomes $ALS'G the $ ?

  • 8/13/2019 11266 Plsql Tutorial

    82/186

  • 8/13/2019 11266 Plsql Tutorial

    83/186

    Simply Easy Learning Page 48

  • 8/13/2019 11266 Plsql Tutorial

    84/186

    Nested 'oops &n PL/SQLPL/SQL allo"s using one loop inside another loop. $ollo"ing section sho"s %e" e0amplesto illustrate the concept.

    The synta0 %or a nested 8asic L P statement in PL/SQL is as %ollo"s5

    L''%7equence o9 state!entsL''%

    7equence o9 state!ents,END L''% *

    END L''% *

    The synta0 %or a nested $ ? L P statement in PL/SQL is as %ollo"s5

    'R counter IN initial5+alue 66 9inal5+alue L''%sequence5o95state!ents

    '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!ents31ILE condition, L''%

    sequence5o95state!ents,END L''% *

    END L''% *

    )(a.p'eThe %ollo"ing program uses a nested 8asic loop to %ind the prime num8ers %rom to # 5

    DECLAREi nu!ber =#*

    nu!ber =#*BEGIN

    i . , *L''%

    . , *L''%

    e it 31EN !od i 2 # - # or i ##*. H *

    END L''% *

    I i # &1ENdb!s5output 6 put5line i 0 is pri!e0 #*END I *i . i H *e it 31EN i - *END L''% *

    END*/

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

    TUTORIALSPOINTSimply Easy Learning Page 49

  • 8/13/2019 11266 Plsql Tutorial

    85/186

    , is pri!e= is pri!e

    is pri!eJ is pri!e

    is pri!e

    = is pri!eJ is pri!eK is pri!e

    ,= is pri!e,K is pri!e= is pri!e=J is pri!eF is pri!eF= is pri!eFJ is pri!e

    %L/78L procedure success9ully co!pleted6

    La e'&ng a PL/SQL LoopPL/SQL loops can 8e la8eled. The la8el should 8e enclosed 8y dou8le angle 8rac ets : and

    ;and appear at the 8eginning o% the L P statement. The la8el name can also appear atthe end o% the L P statement. Eou may use the la8el in the ' 6T statement to e0it %rom theloop.

    The %ollo"ing program illustrates the concept5

    DECLAREi nu!ber #*

    nu!ber #*BEGIN

    >'R i IN 6 6= L''%

    >'R IN 6 6 = L''%

    db!s5output 6put5line 0i is. 0 i 0 and is. 0 #*END loop inner5loop *

    END loop outer5loop *END*/

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

    i is. and is. i is. and is. ,i is. and is. =i is. , and is.

    i is. , and is. ,i is. , and is. =i is. = and is. i is. = and is. ,i is. = and is. =

    %L/78L procedure success9ully co!pleted6

    TUTORIALSPOINTSimply Easy Learning Page 5

  • 8/13/2019 11266 Plsql Tutorial

    86/186

    T*e Loop ontro' State.entsLoop control statements change e0ecution %rom its normal sequence. 4hen e0ecution lea!esa 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 ta ing thecontrol outside a loop. Clic the %ollo"ing lin s to chec their detail.

    Control %tate*ent Description

    ' 6T statement The '0it statement completes the loop and control passes to thestatement immediately a%ter 'ND L P

    C NT6N7' statementCauses the loop to s ip the remainder o% its 8ody and immediatelyretest its condition prior to reiterating.

    B T statement Trans%ers control to the la8eled statement. Though it is not ad!ised touse B T statement in your program.

    )>IT state.entThe ' ,0 statement in PL/SQL programming language has %ollo"ing t"o usages5 4hen the ' 6T 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 ' 6T statement "illstop the e0ecution o% the innermost loop and start e0ecuting the ne0t line o% code a%ter the8loc .

    S nta(

    The synta0 %or a ' 6T statement in PL/SQL is as %ollo"s5

    E$I& *

    F'o= 0&agra.

    TUTORIALSPOINTSimply Easy Learning Page 51

  • 8/13/2019 11266 Plsql Tutorial

    87/186

    )(a.p'eDECLARE

    a nu!ber , # . - *BEGIN

    :: Q(ile loop e ecution31ILE a < ,- L''%db!s5output 6 put5line 0+alue o9 a. 0 a #*a . a H *I a > &1EN

    :: ter!inate t(e loop usin) t(e e it state!entE$I& *

    END I *END L''% *

    END*/

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

    +alue o9 a. -+alue o9 a. +alue o9 a. ,+alue o9 a. =+alue o9 a. F+alue o9 a.

    %L/78L procedure success9ully co!pleted6

    T*e )>IT -,)NState.ent

    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 ' 6T 43'Nstatement5

    7ntil the condition is trueG the ' 6T

  • 8/13/2019 11266 Plsql Tutorial

    88/186

    TUTORIALSPOINTSimply Easy Learning Page 52

  • 8/13/2019 11266 Plsql Tutorial

    89/186

    db!s5output 6 put5line 0+alue o9 a. 0 a #*a . a H *:: ter!inate t(e loop usin) t(e e it Q(en state!ent

    E$I& 31EN a > *END L''% *

    END*/

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

    +alue o9 a. -+alue o9 a. +alue o9 a. ,+alue o9 a. =+alue o9 a. F+alue o9 a.

    %L/78L procedure success9ully co!pleted6

    ONTINU)state.entThe C N0,NG' statement causes the loop to s ip the remainder o% its 8ody andimmediately retest its condition prior to reiterating. 6n other "ordsG it %orces the ne0t iterationo% the loop to ta e placeG s ipping any code in 8et"een.

    S nta(

    The synta0 %or a C NT6N7' statement is as %ollo"s5

    C'N&IN E *

    F'o= 0&agra.

  • 8/13/2019 11266 Plsql Tutorial

    90/186

    TUTORIALSPOINTSimply Easy Learning Page 53

  • 8/13/2019 11266 Plsql Tutorial

    91/186

    )(a.p'eDECLARE

    a nu!ber , # . - *BEGIN

    :: Q(ile loop e ecution31ILE a < ,- L''%db!s5output 6 put5line 0+alue o9 a. 0 a #*a . a H *I a &1EN

    :: sMip t(e loop usin) t(e C'N&IN E state!enta . a H *C'N&IN E *

    END I *END L''% *

    END*/

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

    +alue o9 a. -+alue o9 a. +alue o9 a. ,+alue o9 a. =+alue o9 a. F+alue o9 a. +alue o9 a. J+alue o9 a. +alue o9 a. K

    %L/78L procedure success9ully co!pleted6

    ?OTOstate.ent

    A + 0 statement in PL/SQL programming language pro!ides an unconditional 9ump %romtheB T to a la8eled statement in the samesu8program.

    N 0'< 7se o% B T statement is highly discouraged in any programming language 8ecause itma es di%%icult to trace the control %lo" o% a programG ma ing the program hard to understandand hard to modi%y. Any program that uses a B T can 8e re"ritten so that it doesn2t needthe B T .

    S nta(The synta0 %or a B T statement in PL/SQL is as %ollo"s5

    G'&' label *6666>state!ent *

  • 8/13/2019 11266 Plsql Tutorial

    92/186

  • 8/13/2019 11266 Plsql Tutorial

    93/186

    F'o= 0&agra.

    )(a.p'eDECLARE

    a nu!ber , # . - *BEGIN

    :: Q(ile loop e ecution31ILE a < ,- L''%

    db!s5output 6 put5line 0+alue o9 a. 0 a #*a . a H *I a &1EN

    a . a H *G'&' loopstart *

    END I *END L''% *

    END*/

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

    +alue o9 a. -+alue o9 a. +alue o9 a. ,+alue o9 a. =+alue o9 a. F+alue o9 a. +alue o9 a. J+alue o9 a. +alue o9 a. K

    %L/78L procedure success9ully co!pleted6

    TUTORIALSPOINTSimply Easy Learning Page 55

  • 8/13/2019 11266 Plsql Tutorial

    94/186

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

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

    A B T statement cannot 8ranch into an 6$ statementG CAS' statementG L P statementGor su8

  • 8/13/2019 11266 Plsql Tutorial

    95/186

    Str n,s

    CHAPTER

    1-This chapter describes the conceptsunder strings:

    T he string in PL/SQL is actually a sequence o% characters "ith an optional si>especi%ication. The characters could 8e numericG lettersG 8lan G special characters or acom8ination o% all. PL/SQL o%%ers three inds o% strings5

    "ixed5lengt# strings 5 6n such stringsG programmers speci%y the length "hile declaringthe string. The string is right

  • 8/13/2019 11266 Plsql Tutorial

    96/186

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

    TUTORIALSPOINTSimply Easy Learning Page 57

  • 8/13/2019 11266 Plsql Tutorial

    97/186

    introduction clob *c(oice c(ar #*

    BEGINna!e . 0So(n 7!it(0 *co!pany . 0In9otec(0 *

    introduction . 0 1ello4 I00! So(n 7!it( 9ro! In9otec(60 *c(oice . 0y0 *I c(oice 0y0 &1EN

    db!s5output 6 put5line na!e #*db!s5output 6 put5line co!pany #*db!s5output 6 put5line introduction #*

    END I *END*/

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

    So(n 7!it(In9otec( Corporation1ello4 I0! So(n 7!it( 9ro! In9otec(6

    %L/78L procedure success9ully co!pleted

    To declare a %i0ed

  • 8/13/2019 11266 Plsql Tutorial

    98/186

    -('N+0-! x3?eturns the length o% a character string in 8ytes %or single 8yte character set.

    ( I'R x3Con!erts the letters in 0 to lo"ercase and returns that string.

    #(/)D x8 widt# K8 pad_stringL3 Pads 0 "ith spaces to le%tG to 8ring the total length o% the string up to "idth characters.

    ##(0R,M x K8 tri*_stringL3Trims characters %rom the le%t o% 0.

    N)NF( x8 alue3# ?eturns !alue i% 0 matches the NaN special !alue :not a num8er;G other"ise 0 is

    returned.

    N(%_,N,0C)/ x3#( Same as the 6N6TCAP %unction e0cept that it can use a di%%erent sort method as speci%ied

    8y NLSS ?T.

    N(%_( I'R x3

    #) Same as the L 4'? %unction e0cept that it can use a di%%erent sort method asspeci%ied 8y NLSS ?T.

    N(%_G//'R x3#* Same as the 7PP'? %unction e0cept that it can use a di%%erent sort method as speci%ied

    8y NLSS ?T.

    N(%% R0 x3#+ Changes the method o% sorting the characters. ust 8e speci%ied 8e%ore any NLS

    %unctionI other"iseG the de%ault sort "ill 8e used.

    #,NF( x8 alue3?eturns !alue i% 0 is nullI other"iseG 0 is returned.

    #-NF(2 x8 alue18 alue23?eturns !alue# i% 0 is not nullI i% 0 is nullG !alue is returned.

    #R'/()C' x8 searc#_string8 replace_string3Searches 0 %or searchFstring and replaces it "ith replaceFstring.

    R/)D x8 widt# K8 pad_stringL3Pads 0 to the right.

    #R0R,M x K8 tri*_stringL3Trims 0 %rom the right.

    % GND' x3 ?eturns a string containing the phonetic representation o% 0.

    %G!%0R x8 start K8 lengt#L3( ?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! x3

    ) Same as S71ST? e0cept the parameters are e0pressed in 8ytes instead o% characters%or the single

  • 8/13/2019 11266 Plsql Tutorial

    99/186

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

    )(a.p'e 1DECLARE

    )reetin)s +arc(ar, # . 0(ello Qorld0 *BEGINdb!s5output 6put5line %%ER )reetin)s ##*

    db!s5output 6put5line L'3ER )reetin)s ##*

    db!s5output 6put5line INI&CA% )reetin)s ##*

    /; retrie+e t(e 9irst c(aracter in t(e strin) ;/db!s5output 6put5line 7 B7&R )reetin)s 2 2 ##*

    /; retrie+e t(e last c(aracter in t(e strin) ;/db!s5output 6put5line 7 B7&R )reetin)s 2 : 2 ##*

    /; retrie+e 9i+e c(aracters2startin) 9ro! t(e se+ent( position6 ;/

    db!s5output 6put5line 7 B7&R )reetin)s 2 J 2 ##*

    /; retrie+e t(e re!ainder o9 t(e strin)2startin) 9ro! t(e second position6 ;/

    db!s5output 6put5line 7 B7&R )reetin)s 2 , ##*

    /; 9ind t(e location o9 t(e 9irst "e" ;/db!s5output 6put5line IN7&R )reetin)s 2 0e0 ##*

    END*/

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

    1ELL' 3'RLD(ello Qorld1ello 3orld(d3orldello 3orld,

    %L/78L procedure success9ully co!pleted6

    )(a.p'e 2DECLARE

    )reetin)s +arc(ar, =- # . 06666661ello 3orld666660 *BEGIN db!s5output 6 put5line R&RI@ )reetin)s 2060 ##*

    db!s5output 6put5line L&RI@ )reetin)s 2 060 ##*db!s5output 6put5line &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

  • 8/13/2019 11266 Plsql Tutorial

    100/186

    6666661ello 3orld

    1ello 3orld66666

    1ello 3orld

    %L/78L procedure success9ully co!pleted6

    TUTORIALSPOINTSimply Easy Learning Page 61

  • 8/13/2019 11266 Plsql Tutorial

    101/186

    Arrays

    CHAPTER

    11This chapter describes conceptsunder #rrays:

    P L/SQL programming language pro!ides a data structure called the =A??AEG "hich canstore a %i0ede sequential collection o% elements o% the same type. A !array is used to store anordered collection o% dataG 8ut it is o%ten more use%ul to thin 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 !aria8lee arrays. 4e "illstudy 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 can8e changed dynamically.

    reat&ng a :arraT pe

    A !array type is created "ith the C?'AT' TEP' statement. Eou must speci%y the ma0imum si>eand the type o% elements stored in the !array.

    The 8asic synta0 %or creating a =??AE type at the schema le!elis5

    CREA&E 'R RE%LACE &?%E +array5type5na!e I7 ARRA? n# o9

    4hereG

  • 8/13/2019 11266 Plsql Tutorial

    102/186

    varray_type_name is a !alid attri8ute nameG

    TUTORIALSPOINTSimply Easy Learning Page 62

  • 8/13/2019 11266 Plsql Tutorial

    103/186

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

    a0imum si>e o% a !array can 8e changed using the ALT'? TEP' statement.

    $or e0ampleG

    CREA&E 'r RE%LACE &?%E na!earray A7 ARRA? =# ' ARC1AR, - #*/

    &ype created 6

    The 8asic synta0 %or creating a =??AE type "ithin a PL/SQL 8loc is5

    &?%E +array5type5na!e I7 ARRA? n # o9

    $or e0ample5

    &?%E na!earray I7 ARRA? # ' ARC1AR, - #*

    &ype )rades I7 ARRA? # ' IN&EGER *

    )(a.p'e 1The %ollo"ing program illustrates using !arrays5

    DECLAREtype na!esarray I7 ARRA? # ' ARC1AR, - #*type )rades I7 ARRA? # ' IN&EGER *na!es na!esarray *!arMs )rades *total inte)er *

    BEGINna!es . na!esarray 0 a+ita0 2 0%rita!0 2 0Ayan0 2 0Ris(a+0 2 0ATiT0 #*!arMs . )rades K 2 KJ 2 J 2 J 2 K, #*total . na!es 6count *db!s5output 6put5line 0&otal 0 total 0 7tudents0 #*

    'R i in 66 total L''%db!s5output 6 put5line 07tudent. 0 na!es i # 0@arMs. 0 !arMs i ##*

    END L''% *END*/

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

    7tudent. a+ita @arMs. K7tudent. %rita! @arMs. KJ

    7tudent. Ayan @arMs. J7tudent. Ris(a+ @arMs. J7tudent. ATiT @arMs. K,

    %L/78L procedure success9ully co!pleted6

    Please note5

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

    TUTORIALSPOINTSimply Easy Learning Page 63

  • 8/13/2019 11266 Plsql Tutorial

    104/186

    Eou can initiali>e the !array elements using the constructor method o% the !arraytypeG "hich has the same name as the !array.

    =arrays are one

  • 8/13/2019 11266 Plsql Tutorial

    105/186

    Proce).res

    CHAPTER

    12This chapter describes the proceduresunder PL/SQL:

    A subprogra* is a program unit/module that per%orms a particular tas . Thesesu8programs are com8ined to %orm larger programs. This is 8asically called the 2 odular design2.

    A su8program can 8e in!o ed 8y another su8program or programG "hich is called thecalling program.

    A su8program can 8e created5

    At schema le!el

    6nside a pac age

    6nside a PL/SQL 8loc

    A schema le!el su8program is a standalone subprogra* . 6t is created "ith theC?'AT' P? C'D7?' or C?'AT' $7NCT6 N statement. 6t is stored in the data8aseand can 8e deleted "ith the D? P P? C'D7?' or D? P $7NCT6 N statement.

    A su8program created inside a pac age is a packaged subprogra* . 6t is stored in thedata8aseand can 8e deleted only "hen the pac age is deleted "ith the D? P PAC@AB' statement. 4e

    "ill discuss pac ages in the chapter 2PL/SQL < Pac ages2.PL/SQL su8programs are named PL/SQL 8loc s that can 8e in!o ed "ith a set o%parameters. PL/SQL pro!ides t"o inds o% su8programs5

    "unctions 5 these su8programs return a single !alueG mainly used to compute and return a!alue.

    /rocedures 5 these su8programs do not return a !alue directlyG mainly used to per%orm anaction.This chapter is going to co!er important aspects o% a /( %H( procedure and "e "illco!er /( %H( function in ne0t chapter.

    Parts of a PL/SQLSu progra.

  • 8/13/2019 11266 Plsql Tutorial

    106/186

    'ach PL/SQL su8program has a nameG and may ha!e a parameter list. Li e anonymousPL/SQL8loc s andG the named 8loc s a su8programs "ill also ha!e %ollo"ing threeparts5

    TUTORIALSPOINTSimply Easy Learning Page 65

  • 8/13/2019 11266 Plsql Tutorial

    107/186

    %.N. /arts & Description

    Declarati e /art6t is an optional part. 3o"e!erG the declarati!e part %or a su8program does not start "ith the

    # D'CLA?' ey"ord. 6t contains declarations o% typesG cursorsG constantsG !aria8lesG

    e0ceptionsG and nested su8programs. These items are local to the su8program andcease to e0ist "hen the su8program completes e0ecution.

    'xecutable /artThis is a mandatory part and contains statements that per%orm the designated action.

    ('xception5#andlingThis is again an optional part. 6t contains the code that handles runEND 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 thisparameter "ill 8e used to return a !alue outside o% the procedure.

    procedure-body contains the e0ecuta8le part.

    The AS ey"ord is used instead o% the 6S ey"ord %or creating a standalone procedure.

    )(a.p'eThe %ollo"ing e0ample creates a simple procedure that displays the string 23ello 4orld 2 onthe screen "hen e0ecuted.

    CREA&E 'R RE%LACE %R'CED RE )reetin)sA7

    BEGINdb!s5output 6put5line 01ello 3orld40 #*

    END*/

    4hen a8o!e code is e0ecuted using SQL promptG it "ill produce the %ollo"ing result5

    %rocedure created6

    TUTORIALSPOINTSimply Easy Learning Page 66

  • 8/13/2019 11266 Plsql Tutorial

    108/186

  • 8/13/2019 11266 Plsql Tutorial

    109/186

    initiali>e it to a de%ault !alueI ho"e!erG in that caseG it is omitted %rom the su8program call. ,t ist#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 7Tparameter acts li e a !aria8le. Eou can change its !alue and re%erence the !alue a%ter assigningit. 0#e actual para*eter *ust be ariable and it is passed bE alue .

    ,N G0 An 6N 7T parameter passes an initial !alue to a su8program and returns an updated !alue tothe 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 aconstant or an e0pression. $ormal parameter must 8e assigned a !alue. )ctual para*eteris passed bE alue.

    IN OUT @ode )(a.p'e 1This program %inds the minimum o% t"o !aluesG here procedure ta es t"o num8ers using6N

    mode and returns their minimum using 7T paramters.DECLARE

    a nu!ber *b nu!ber *c nu!ber *

    %R'CED RE 9ind@in IN nu!ber 2 y IN nu!ber 2 T ' & nu!ber # I7BEGIN

    I < y &1ENT. *

    EL7ET. y*

    END I *END*

    BEGINa . ,= *b . F *9ind@in a 2 b2 c #*db!s5output 6put5line 0 @ini!u! o9 ,=2 F # . 0 c #*

    END*/

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

    @ini!u! o9 ,=2 F # . ,=

    %L/78L procedure success9ully co!pleted6

    IN OUT @ode )(a.p'e 2This 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.

    DECLAREa nu!ber *

    %R'CED RE squareNu! IN ' & nu!ber # I7BEGIN

    . ; *

    TUTORIALSPOINTSimply Easy Learning Page 68

  • 8/13/2019 11266 Plsql Tutorial

    110/186

    END*BEGIN

    a . ,= *squareNu! a #*db!s5output 6put5line 0 7quare o9 ,=#. 0 a #*

    END*/

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

    7quare o9 ,=#. ,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

    i0ed notation

    POSITIONAL NOTATION

    6n positional notationG you can call the procedure as5

    9ind@in a 2 b2 c 2 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 ais su8stituted %or 0G 8 is su8stituted %or yG c is su8stituted %or > and d is su8stituted %or m.

    NA@)0NOTATION

    6n named notationG the actual parameter is associated "ith the %ormal parameter using the arro"sym8ol : R ;. So the procedure call "ould loo li e5

    9ind@in >a 2 y >b 2 T >c 2 ! >d #*

    @I>)0 NOTATION

    6n mi0ed notationG you can mi0 8oth notations in procedure callI ho"e!erG the positionalnotation should precede the named notation.

    The %ollo"ing call is legal5

    9ind@in a 2 b2 c 2 ! >d#*

    1ut this is not legal5

    9ind@in >a 2 b2 c 2 d#*

    TUTORIALSPOINT

  • 8/13/2019 11266 Plsql Tutorial

    111/186

    Simply Easy Learning Page 69

  • 8/13/2019 11266 Plsql Tutorial

    112/186

    .nct ons

    CHAPTER

    13This chapter describes the functions:

    A PL/SQL %unction is same as a procedure e0cept that it returns a !alue. There%oreG allthe discussions o% the pre!ious chapter are true %or %unctions too.

    reat&ng a Fun t&on A standalone %unction is created using the C?'AT' $7NCT6 N statement. Thesimpli%ied synta0 %or the C?'AT' ? ?'PLAC' P? C'D7?' statement is as %ollo"s5

    CREA&E 'R RE%LACE NC&I'N 9unction5na!epara!eter5na!e IN ' & IN ' & type 2 666 #

    RE& RN return5datatypeUI7 A7VBEGIN

    < 9unction5body >END 9unction5na!e *

    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. 6Nrepresents that !alue "ill 8e passed %rom outside and 7T represents that thisparameter "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 ey"ord is used instead o% the 6S ey"ord %or creating a standalone %unction.

  • 8/13/2019 11266 Plsql Tutorial

    113/186

    TUTORIALSPOINTSimply Easy Learning Page 7

  • 8/13/2019 11266 Plsql Tutorial

    114/186

    )(a.p'eThe %ollo"ing e0ample illustrates creating and calling a standalone %unction. This %unction returnsthe total num8er o% C7ST '?S in the customers ta8le. 4e "ill use the C7ST '?S ta8le"hich "e had created in P L /S Q L = a ria 8 le s c hapter5

    7elect ; 9ro! custo!ers *

    H::::H::::::::::H:::::H:::::::::::H::::::::::HID NA@E AGE ADDRE77 7ALAR?

    H::::H::::::::::H:::::H:::::::::::H::::::::::HRa!es( =, A(!edabad ,---6--

    , (ilan , Del(i --6--= Maus(iM ,= ota ,---6--F C(aitali , @u!bai --6--

    1ardiM ,J B(opal --6--o!al ,, @% F --6--

    H::::H::::::::::H:::::H:::::::::::H::::::::::HCREA&E 'R RE%LACE NC&I'N totalCusto!ersRE& RN nu!ber I7

    total nu!ber , # . - *BEGIN

    7ELEC& count ;# into totalR'@ custo!ers *

    RE& RN total *END*/

    4hen a8o!e code is e0ecuted using SQL promptG it "ill produce the %ollo"ing result5

    unction created6

    a''&ng aFun t&on4hile creating a %unctionG you gi!e a de%inition o% "hat the %unction has to do. To use a %unctionGyou "ill ha!e to call that %unction to per%orm the de%ined tas . 4hen a program calls a%unctionG program control is trans%erred to the called %unction.

    A called %unction per%orms de%ined tas and "hen its return statement is e0ecuted or "hen it lastend statement is reachedG it returns program control 8ac to the main program.

    To call a %unction you simply need to pass the required parameters along "ith %unction nameand i% %unction returns a !alue then you can store returned !alue. $ollo"ing programcalls the %unction totalCustomers %rom an anonymous 8loc 5

    DECLAREc nu!ber , #*

    BEGINc . totalCusto!ers #*db!s5output 6put5line 0&otal no6 o9 Custo!ers. 0 c #*

    END*/

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

    http://www.tutorialspoint.com/plsql/plsql_variable_types.htmhttp://www.tutorialspoint.com/plsql/plsql_variable_types.htmhttp://www.tutorialspoint.com/plsql/plsql_variable_types.htmhttp://www.tutorialspoint.com/plsql/plsql_variable_types.htm
  • 8/13/2019 11266 Plsql Tutorial

    115/186

    TUTORIALSPOINTSimply Easy Learning Page 71

  • 8/13/2019 11266 Plsql Tutorial

    116/186

    &otal no6 o9 Custo!ers.

    %L/78L procedure success9ully co!pleted6

    )(a.p'eThe %ollo"ing is one more e0ample "hich demonstrates DeclaringG De%iningG and 6n!o ing aSimple PL/SQL $unction that computes and returns the ma0imum o% t"o !alues.

    DECLAREa nu!ber *b nu!ber *c nu!ber *

    NC&I'N 9ind@a IN nu!ber 2 y IN nu!ber #RE& RN nu!berI7

    T nu!ber *

    BEGINI > y &1ENT. *

    EL7EP. y*

    END I *

    RE& RN T*END*BEGIN

    a . ,= *b . F *

    c . 9ind@a a 2 b#*db!s5output 6put5line 0 @a i!u! o9 ,=2F #. 0 c #*

    END*/

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

    @a i!u! o9 ,=2F #. J

    %L/78L procedure success9ully co!pleted6

    PL/SQL Re urs&ve Fun t&ons4e ha!e seen that a program or su8program may call another su8program. 4hen asu8program calls itsel%G it is re%erred to as a recursi!e call and the process is no"n as recursion.

    To illustrate the conceptG let us calculate the %actorial o% a num8er. $actorial o% a num8er nis de%ined as5

    n4 n ; n: #4n ; n: #; n:, #4

    666n ; n: #; n:, #; n:= #666

    TUTORIALSPOINTSimply Easy Learning Page 72

  • 8/13/2019 11266 Plsql Tutorial

    117/186

    The %ollo"ing program calculates the %actorial o% a gi!en num8er 8y calling itsel% recursi!ely5

    DECLAREnu! nu!ber *9actorial nu!ber *

    NC&I'N 9act nu!ber #RE& RN nu!berI7

    9 nu!ber *BEGIN

    I - &1EN9 .

  • 8/13/2019 11266 Plsql Tutorial

    118/186

    C.rsors

    CHAPTER

    1"This chapter explains cursors under

    PL/SQL:

    O racle creates a memory areaG no"n as conte0t areaG %or processing an SQLstatementG "hich contains all in%ormation needed %or processing the statementG %or e0ampleGnum8er o% ro"s processed etc.

    A cursor is a pointer to this conte0t area. PL/SQL controls the conte0t area through a cursor. Acursor holds the ro"s :one or more; returned 8y a SQL statement. The set o% ro"s thecursor holds is re%erred to as the acti e set .

    Eou can name a cursor so that it could 8e re%erred to in a program to %etch and process the ro"sreturned 8y the SQL statementG one at a time. There are t"o types o% cursors5

    6mplicit cursors

    '0plicit cursors

    I.p'& &tursors

    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 theimplicit cursors and the in%ormation in it.

    4hene!er a D L statement :6NS'?TG 7PDAT' and D'L'T'; is issuedG an implicit cursor isassociated "ith this statement. $or 6NS'?T operationsG the cursor holds the data that need to8e 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( cursor G "hich al"ayshas the attri8utes li e $ 7NDG 6S P'NG N T$ 7NDG and ? 4C 7NT. The SQLcursor has additional attri8utesG 17L@F? 4C 7NT and 17L@F' C'PT6 NSG designed%or use "ith the $ ?ALL statement. The %ollo"ing ta8le pro!ides the description o% themost used attri8utes5

    )ttribute Description

  • 8/13/2019 11266 Plsql Tutorial

    119/186

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

    TUTORIALSPOINTSimply Easy Learning Page 74

  • 8/13/2019 11266 Plsql Tutorial

    120/186

    one or more ro"s or a S'L'CT 6NT statement returned one or morero"s. ther"iseG it returns $ALS'.

    N T$ 7NDThe logical opposite o% $ 7ND. 6t returns T?7' i% an 6NS'?TG7PDAT'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'.

    6S P'N Al"ays returns $ALS' %or implicit cursorsG 8ecause racle closes theSQL cursor automatically a%ter e0ecuting its associated SQL statement.

    ? 4C 7NT ?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.

    Any SQL cursor attri8ute "ill 8e accessed as s l:attribute_na*e as sho"n 8elo" in thethe e0ample.

    )(a.p'e4e "ill 8e using the C7ST '?S ta8le "e had created and used in the pre!ious chapters.

    7elect ; 9ro! custo!ers *

    H::::H::::::::::H:::::H:::::::::::H::::::::::HID NA@E AGE ADDRE77 7ALAR?

    H::::H::::::::::H:::::H:::::::::::H::::::::::HRa!es( =, A(!edabad ,---6--

    , (ilan , Del(i --6--= Maus(iM ,= ota ,---6--F C(aitali , @u!bai --6--

    1ardiM ,J B(opal --6--o!al ,, @% F --6--

    H::::H::::::::::H:::::H:::::::::::H::::::::::H

    The %ollo"ing program "ould update the ta8le and increase salary o% each customer 8y *

    and use the SQL ? 4C 7NT attri8ute to determine the num8er o% ro"s a%%ected5

    DECLAREtotal5roQs nu!ber , #*

    BEGIN%DA&E custo!ers

    7E& salary salary H -- *I sql Onot9ound &1EN

    db!s5output 6 put5line 0no custo!ers selected0 #*EL7I sql O9ound &1EN

    total5roQs . sql OroQcount *db!s5output 6 put5line total5roQs 0 custo!ers selected 0 #*

    END I *END*/

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

    custo!ers selected

    %L/78L procedure success9ully co!pleted6

    6% you chec the records in customers ta8leG you "ill %ind that the ro"s ha!e 8een updated5

    TUTORIALSPOINTSimply Easy Learning Page 75

  • 8/13/2019 11266 Plsql Tutorial

    121/186

    7elect ; 9ro! custo!ers *

    H::::H::::::::::H:::::H:::::::::::H::::::::::HID NA@E AGE ADDRE77 7ALAR?

    H::::H::::::::::H:::::H:::::::::::H::::::::::H

    Ra!es( =, A(!edabad , --6--, (ilan , Del(i ,---6--= Maus(iM ,= ota , --6--F C(aitali , @u!bai J---6--

    1ardiM ,J B(opal K---6--o!al ,, @% ---6--

    H::::H::::::::::H:::::H:::::::::::H::::::::::H

    )(p'& &tursors

    '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 1loc . 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 *

    4or ing "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

    0e 'ar&ng t*e ursorDeclaring the cursor de%ines the cursor "ith a name and the associated S'L'CT statement.$or e0ample5

    C R7'R c5custo!ers I77ELEC& id 2 na!e 2 address R'@ custo!ers *

    Open&ng t*eursor

    pening the cursor allocates memory %or the cursorG and ma es it ready %or %etching thero"s returned 8y the SQL statement into it. $or e0ampleG "e "ill open a8o!e de%inedcursor as %ollo"s5

    '%EN c5custo!ers *

    Fet *&ng t*e ursor$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

  • 8/13/2019 11266 Plsql Tutorial

    122/186

    TUTORIALSPOINTSimply Easy Learning Page 76

  • 8/13/2019 11266 Plsql Tutorial

    123/186

    E&C1 c5custo!ers IN&' c5id 2 c5na!e 2 c5addr *

    'os&ng t*e ursorClosing the cursor means releasing the allocated memory. $or e0ampleG "e "ill closea8o!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

    DECLAREc5id custo!ers 6 id Otype *c5na!e custo!ers 6na!e Otype *c5addr custo!ers 6 address Otype *C R7'R c5custo!ers is

    7ELEC& id 2 na!e 2 address R'@ custo!ers *BEGIN

    '%EN c5custo!ers *L''%

    E&C1 c5custo!ers into c5id 2 c5na!e 2 c5addr *db!s5output 6 put5line c5id 0 0 c5na!e 0 0c5addr #* E$I& 31EN c5custo!ers Onot9ound *

    END L''% *CL'7E c5custo!ers *

    END*/

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

    Ra!es( A(!edabad, (ilan Del(i= Maus(iM otaF C(aitali @u!bai

    1ardiM B(opal o!al @%

    %L/78L procedure success9ully co!pleted6

    TUTORIALSPOINTSimply Easy Learning Page 77

  • 8/13/2019 11266 Plsql Tutorial

    124/186

    Recor)s

    CHAPTER

    1&This chapter describes $ecords in Pl/SQL which is adata structure:

    A PL/SQL record is a data structure that can hold data items o% di%%erent inds. ?ecordsconsist o% di%%erent %ieldsG similar to a ro" o% a data8ase ta8le.

    $or e0ampleG you "ant to eep trac o% your 8oo s in a li8rary. Eou might "ant to tracthe %ollo"ing attri8utes a8out each 8oo li eG TitleG AuthorG Su89ectG 1oo 6D. A recordcontaining a %ield %or each o% these items allo"s treating a 1 @ as a logical unit and allo"s

    you to organi