Oracle Database 11g PLSQL Variables Attributes and Executable Statements

Embed Size (px)

Citation preview

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    1/61

    | Print| Contents| Close|

    Using PL/SQL Development Environments

    Learning objective

    After completing this topic, you should be able to recognize the features and capabilities

    of SQL Developer, SQL*Plus, and JDeveloper

    1. Introducing PL/SQL development tools

    Disclaimer

    Although certain aspects of Oracle Database 11g are case and spacing insensitive, a

    common coding convention has been used throughout all aspects of this course.

    This convention uses lowercase characters for schema, role, user, and constraint names,

    and for permissions, synonyms, and table names (with the eception of the D!A" table#.

    "owercase characters are also used for column names and user$defined procedure,

    function, and variable names shown in code.

    !ppercase characters are used for Oracle %eywords and functions, for view, table,

    schema, and column names shown in tet, for column aliases that are not shown in

    &uotes, for pac%ages, and for data dictionary views.

    The spacing convention re&uires one space after a comma and one space before and

    after operators that are not Oracle$specific, such as ', $, , and ). There should be nospace between an Oracle$specific %eyword or operator and an opening brac%et, a closing

    brac%et and a comma, between the last part of a statement and the closing semicolon, or

    before a statement.

    *tring literals in single &uotes are an eception to all convention rules provided. +lease

    use this convention for all interactive parts of this course.

    $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

    There are many tools that provide an environment for developing +"*" code. Oracle

    provides several tools that can be used to write +"*" code.

    *ome of the development tools include-

    Oracle *" Developer

    Oracle *"+lus

    Oracle /Developer

    racle SQL Developer

    http://%20window.print%28%29/http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20parent.window.close%28%29/http://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20window.print%28%29/
  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    2/61

    Oracle *" Developer is a graphical tool that can be used to write +"*" code.

    racle SQL!Plus

    Oracle *"+lus is a window or command$line application that can be used to write

    +"*" code.

    racle "Developer

    Oracle /Developer is a window$based integrated development environment (0D# that can

    be used to write +"*" code.

    Oracle *" Developer is a free graphical tool designed to improve your productivity and

    simplify the development of everyday database tas%s. 2ith 3ust a few clic%s, you can

    easily create and debug stored procedures, test *" statements, and view optimi4er

    plans.

    *" Developer, the visual tool for database development, simplifies these tas%s-

    browsing and managing database ob3ects

    eecuting *" statements and scripts

    editing and debugging +"*" statements

    creating reports

    5ou can connect to any target Oracle database schema by using standard Oracle

    database authentication. 2hen connected, you can perform operations on ob3ects in the

    database.

    Oracle *"+lus is a command$line application that enables you to submit *"

    statements and +"*" bloc%s for eecution, and receive the results in an application or

    command window.

    *"+lus is

    shipped with the database

    installed on a client and on the database server system

    accessed from an icon or the command line

    Oracle /Developer allows developers to create, edit, test, and debug +"*" code by

    using a sophisticated graphical user interface (6!0#. Oracle /Developer is a part ofOracle Developer *uite and is also available as a separate product.

    2hen coding +"*" in /developer, you should consider these points-

    5ou create a database connection to enable /Developer to access a database schema owner for

    the subprograms.

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    3/61

    5ou can then use the /Developer shortcut menus on the database connection to create a new

    subprogram construct using the built$in /Developer 7ode ditor. This ditor provides an ecellent

    environment for +"*" development, with features such as different colors for syntactical

    components of the +"*" language and code insight to rapidly locate procedures and functions in

    supplied pac%ages.

    This is the final point to be considered when coding +"*" in /Developer-

    5ou invo%e a subprogram by using a Runcommand on the shortcut menu for the named

    subprogram. The output appears in the /Developer "og 8essage window.

    #ote

    JDeveloper provides color-coding syntax in the JDeveloper Code Editor and is

    sensitive to PL/SQL language constructs and statements.

    Question

    2hich statements best describe functionality capabilities in *" Developer9

    Options-

    1. *" Developer can be used for browsing and managing database ob3ects

    :. *" Developer can be used for editing and debugging +"*" statements

    ;. *" Developer cannot be used for creating Oracle *" reports

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    4/61

    &. Using SQL Developer

    To create a database connection using *" Developer, you perform these steps-

    Step 1- Double$clic% )yourpath=>s&ldeveloper>s&ldeveloper.ee.

    Step &- On the 7onnections tabbed page, right$clic% Connectionsand select #e%

    Connection.

    Step '- 0n the ?ew *elect Database 7onnection dialog bo, specify the 7onnection

    ?ame, !sername, and +assword.

    The net steps to create a database connection are

    Step (- *pecify the @ostname and *0D for the database you want to connect to.

    Step )- 7lic% *estto ensure that the connection has been set correctly.

    Step +- 7lic% Connect.

    0n the ?ew *elect Database 7onnection dialog bo, on the Oracle tabbed page, you

    specify these options-

    @ostname, which is the host system for the Oracle database

    +ort, which is the listener port

    *0D, which is the database name

    *ervice name, which is the networ% service name for a remote database connection

    0f you select the Save Pass%ordchec% bo, the password is saved to an 8" file. As a

    result, you are not prompted for the password after you close the *" Developer

    connection and open it again.

    5ou can create any schema ob3ect in *" Developer by using one of these methods-

    eecuting a *" statement in *" 2or%sheet

    using the shortcut menu

    5ou can edit schema ob3ects by using the dit dialog bo or one of the many contet$

    sensitive menus.

    5ou can also view the data definition language (DD"# for ad3ustments such as creating a

    new ob3ect or editing an eisting schema ob3ect.

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    5/61

    2hen you connect to a database, a *" 2or%sheet window for that connection is

    automatically opened. 5ou can use the *" 2or%sheet to enter and eecute *",

    +"*", and *"+lus statements.

    The *" 2or%sheet supports *"+lus statements to a certain etent. *"+lus

    statements that are not supported by the *" 2or%sheet are ignored and are not passed

    to the database.

    2ithin a wor%sheet, you can specify various database manipulation and definition

    connection actions, such as

    creating a table

    inserting data

    creating and editing a trigger

    selecting data from a table

    saving the selected data to a file

    5ou can display a *" 2or%sheet by using either of these options-

    select *ools= SQL ,or-seet

    clic% the pen SQL ,or-seeticon

    0n the *" 2or%sheet, you can use the nter *" *tatement bo to enter single or

    multiple *" statements. Bor a single statement, the semicolon at the end is optional.

    2hen you enter the statement, the *" %eywords are automatically highlighted. To

    eecute a *" statement, ensure that your cursor is within the statement and then clic%

    Eecute Statement. Alternatively, you can press the 023%ey.

    To eecute multiple *" statements and see the results, clic% 4un Scriptor press ).

    @ere is a sample *" statement in which the first statement is terminated with a

    semicolon because there are multiple *" statements. The cursor is in the first

    statement. Therefore, when the statement is eecuted, results corresponding to the first

    statement are displayed in the Cesults bo.

    Question

    2hich statement is true about using the *" 2or%sheet9

    Options-

    1. 0n the *" 2or%sheet, you can eecute *" and +"*" statements

    :. *"+lus statements cannot be interpreted by *" 2or%sheet

    ;. *tatements not supported by the *" 2or%sheet are passed on to the database

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    6/61

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    7/61

    Summar5

    Oracle provides several tools that can be used to write +"*" code. These tools include

    Oracle *" Developer, Oracle *"+lus, and Oracle /Developer. Oracle *" Developer

    is a free graphical tool that helps improve your productivity and simplify the development

    of everyday database tas%s. Oracle *"+lus is a command$line application that enables

    you to submit *" statements and +"*" bloc%s for eecution and receive results in an

    application or command window. Oracle /Developer allows you to create, edit, test, and

    debug +"*" code by using a sophisticated 6!0.

    5ou can create database connections and schema ob3ects using *" Developer. 5ou can

    use the *" 2or%sheet to enter and eecute *", +"*", and *"+lus statements.

    To eecute a *" statement, you clic% Eecute Statementor press the 2%ey.

    *able o6 Contents

    | *op o6 page|

    | Learning objective|

    | 1. Introducing PL/SQL development tools|

    | &. Using SQL Developer|

    | Summar5|

    7opyright :EEF *%ill*oft. All rights reserved.

    *%ill*oft and the *%ill*oft logo are trademar%s or registered trademar%sof *%ill*oft in the !nited *tates and certain other countries.

    All other logos or trademar%s are the property of their respective owners.

    | Print| Contents| Close|

    Introducing PL/SQL

    Learning objective

    After completing this topic, you should be able to identify the features and benefits of

    PL!SQL and identify the steps for building basic PL!SQL bloc"s

    1. vervie% o6 PL/SQL

    *tructured uery "anguage (*"# is the primary language used to access and modify

    data in a relational database. Gecause there are only a few *" commands, you can

    easily learn and use them.

    http://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257801/257804/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20parent.window.close%28%29/http://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257801/257803/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257801/257804/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/
  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    8/61

    7onsider this sample *" statement, which is simple and straightforward. @owever, if

    you want to alter any data that is retrieved in a conditional manner, you will encounter the

    limitations of *".

    SELECT first_name, department_id, saar! "R#$ emp%!ees&

    *ay you want to retrieve data for every employee, their department 0D, and salary. 5ou

    also want to give varying bonuses to these employees, depending on their departmentHs

    performance and the employeeHs salary.

    To do this, you need to eecute the SELECT*" statement, collect the data, and apply

    logic to the data. One solution is to write a *" statement for each department to give

    bonuses to the employees in that department. ?ote that you also have to chec% the salary

    component before deciding the bonus amount. This ma%es it a little complicated. 5ou now

    feel that it would be much easier if you had conditional statements. +"*" (+rocedural

    "anguage etension to *tructured uery "anguage# is designed to meet such

    re&uirements. 0t provides a programming etension to the already$eisting *".

    +"*" defines a bloc% structure for writing eecutable units of code. 8aintaining and

    debugging the code is easier with such a well$defined structure. 5ou can easily

    understand the flow and eecution of the program unit.

    +"*" offers modern software engineering features such as data encapsulation,

    eception handling, information hiding, and ob3ect orientation. 0t brings state$of$the$art

    programming to the Oracle server and toolset.

    +"*" provides these procedural constructs that are available in any third$generation

    language (;6"#-

    variables, constants, and data types

    control structures such as conditional statements and loops

    reusable program units that are written once and eecuted many times

    0n a +"*" eecution environment of an Oracle database server, a +"*" bloc%

    contains procedural statements and *" statements. 2hen you submit the +"*" bloc%

    to the server, the +"*" engine first parses the bloc%. The +"*" engine identifies the

    procedural statements and the *" statements. 0t passes the procedural statements to

    the procedural statement eecutor and the *" statements to the *" statement

    eecutor individually.

    The Oracle application development tools can also contain a +"*" engine. The tool

    passes the bloc%s to its local +"*" engine. Therefore, all procedural statements are

    eecuted locally and only the *" statements are eecuted in the database. The engine

    used depends on where the +"*" bloc% is being invo%ed from.

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    9/61

    These are the benefits of using +"*"-

    integration of procedural constructs with *"

    improved performance

    implementation of modulari4ed program development

    integration with tools

    portability

    eception handling

    The most important advantage of +"*" is the integration of procedural constructs with

    *". *" is a nonprocedural language. 2hen you issue a *" command, the command

    tells the database server what to do. @owever, you cannot specify how to do it. +"*"

    integrates control statements and conditional statements with *", giving you better

    control of your *" statements and their eecution.

    2ithout +"*", you would not be able to logically combine *" statements as one unit.0f you have designed an application containing forms, you may have many different forms

    with fields in each form.

    2hen a form submits the data, you may have to eecute a number of *" statements,

    which are sent to the database one at a time. This results in many networ% trips and one

    call to the database for each *" statement, thereby increasing networ% traffic and

    reducing performance, especially in a clientserver model.

    2ith +"*", you can combine all these *" statements into a single program unit. The

    application can then send the entire bloc% of statements to the database, instead of

    sending the *" statements one at a time. This significantly reduces the number ofdatabase calls. 0f the application is *" intensive, you can use +"*" bloc%s to group

    *" statements before sending them to the Oracle database server for eecution, thus

    improving performance.

    A basic unit in all +"*" programs is the bloc%. Gloc%s can be in a se&uence or they can

    be nested in other bloc%s. Gy implementing modulari4ed program development, you can

    group logically related statements within bloc%s

    nest bloc%s inside larger bloc%s to build powerful programs

    brea% your application into smaller, manageable, and logically related modules, if you aredesigning a comple application

    maintain and debug the code

    0n +"*", modulari4ation is implemented using procedures, functions, and pac%ages.

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    10/61

    The +"*" engine is integrated in Oracle tools such as Oracle Borms and Oracle

    Ceports. 2hen you use these tools, the locally available +"*" engine processes the

    procedural statementsI only the *" statements are passed to the database.

    +"*" programs are portable and can run anywhere an Oracle server runs, irrespective

    of the operating system and the platform. 5ou do not need to customi4e them to each

    new environment. 5ou can write portable program pac%ages and create libraries that can

    be reused in different environments.

    +"*" enables you to handle eceptions efficiently. 5ou can define separate bloc%s for

    dealing with eceptions. +"*" shares the same data type system as *", with some

    etensions, and uses the same epression synta.

    &. PL/SQL bloc- structure

    A basic +"*" bloc% structure can include these %eywords-

    DECLARE

    BE'IN

    E(CEPTI#N

    END

    These three sections can be identified in a +"*" bloc%-

    declarative

    eecutable eception handling

    declarative

    The declarative section begins with the %eyword DECLAREand ends when the eecutable

    section starts. This section contains declarations of all variables, constants, cursors, and

    user$defined eceptions that are referenced in the eecutable and eception sections. The

    inclusion of the declarative section is optional.

    eecutable

    The eecutable section begins with the %eyword BE'INand ends with END. This section

    essentially needs to have at least one statement and includes any number of +"*"bloc%s to manipulate data in a bloc%. This section contains *" statements to retrieve data

    from the database. The inclusion of the eecutable section is mandatory.

    eception andling

    The eception section is nested within the eecutable section. This section begins with the

    %eyword E(CEPTI#Nand specifies the actions to perform when errors and abnormal

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    11/61

    conditions arise in the eecutable section. The inclusion of the eception handling section

    is optional.

    0n a +"*" bloc%, the %eywords DECLARE, BE'IN, and E(CEPTI#Nare not terminated

    by a semicolon. @owever, the %eyword END, all *" statements, and +"*" statements

    must be terminated with a semicolon.

    A +"*" program comprises one or more bloc%s. These bloc%s can be entirely separate

    or nested within another bloc%. These are the three types of bloc%s that ma%e up a

    +"*" program-

    anonymous bloc%s

    )code=)DECLARE* BE'IN ++statements )E(CEPTI#N* END&)code=

    procedures

    )code=PR#CEDURE name IS BE'IN ++statements )E(CEPTI#N* END&)code=

    functions

    )code="UNCTI#N name RETURN datat!pe IS BE'IN ++statements RETURN

    aue& )E(CEPTI#N*END&)code=

    Anonymous bloc%s are unnamed bloc%s. They are declared inline at the point in an

    application where they are to be eecuted and are compiled each time the application is

    eecuted. These bloc%s are not stored in the database. They are passed to the +"*"

    engine for eecution at run time. Triggers in Oracle Developer components consist of

    such bloc%s. These anonymous bloc%s get eecuted at run time because they are inline.

    0f you want to eecute the same bloc% again, you have to rewrite the bloc%. 5ou are

    unable to invo%e or call the bloc% that you wrote earlier because bloc%s are anonymous

    and do not eist after they are eecuted.

    *ubprograms are complementary to anonymous bloc%s. They are named +"*" bloc%s

    that are stored in the database. Gecause they are named and stored, you can invo%e

    them whenever you want, depending on your application. 5ou can declare them either as

    procedures or as functions. 5ou typically use a procedure to perform an action and a

    function to compute and return a value.

    #ote

    3 'unction is similar to a procedure& except that a 'unction must return a value.

    5ou can store subprograms at the server or application level. !sing Oracle Developer

    components, such as forms or reports, you can declare procedures and functions as part

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    12/61

    of the application, which might be a form or a report, and call them from other procedures,

    functions, and triggers within the same application whenever necessary.

    These are the +"*" program constructs that use the basic +"*" bloc%s and are

    based on the environment in which they are eecuted-

    anonymous bloc%s

    application procedures or functions

    stored procedures or functions

    application or stored pac%ages

    database triggers

    application triggers

    ob3ect types

    anon5mous bloc-s

    Anonymous bloc%s are embedded within an application or are issued interactively and are

    available to all +"*" environments.

    application procedures or 6unctions

    Application procedures or functions are named +"*" bloc%s stored in an Oracle Borms

    Developer application or shared library. 0t can accept parameters and can be invo%ed

    repeatedly by name. This program construct is available for Oracle Developer tools

    components, for eample, Oracle Borms Developer and Oracle Ceports.

    stored procedures or 6unctions

    *tored procedures or functions are named +"*" bloc%s stored in the Oracle server and

    accept parameters. These can be invo%ed repeatedly by name and are available to Oracleserver or Oracle Developer tools.

    application or stored pac-ages

    Application or stored pac%ages are named +"*" modules that group related procedures,

    functions, and identifiers. They are available to Oracle server and Oracle Developer tools

    components, such as Oracle Borms Developer.

    database triggers

    Database triggers are +"*" bloc%s that are associated with a database table, and are

    fired automatically when triggered by various events. They are available to Oracle server

    or any Oracle tools that issue the D8".application triggers

    Application triggers are +"*" bloc%s that are associated either with a database table or

    system events. They are fired automatically when triggered by a D8" or a system event

    respectively. They are available to Oracle Developer tools components, such as Oracle

    Borms Developer.

    object t5pes

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    13/61

    Ob3ect types are user$defined composite data types that encapsulate a data structure

    along with the functions and procedures needed to manipulate the data. These bloc%s are

    available to Oracle server and Oracle Developer tools.

    To create an anonymous bloc% by using *" Developer, you need to eecute these

    steps-

    Step 1- nter the anonymous bloc% in the *" Developer wor%space. The anonymous

    bloc% gets the first_nameof the employee whose emp%!ee_idis -.., and stores it

    in a variable called _fname. 7lic% 4un Scriptto eecute the anonymous bloc%.

    Step &7After the bloc% is eecuted, the message Janonymous bloc% completedJ is

    displayed in the *cript Output window.

    +"*" does not have built$in input or output functionality. Therefore, you need to use

    predefined Oracle pac%ages for input and output. The output of the +"*" bloc% after

    the inclusion of the code for generating output is displayed. To get the output that is to bedisplayed, you perform these steps-

    Step 17 7lic% the D89S utputtab. Then you clic% Enable D89S utput. This

    eecutes the SET SERVER#UTPUT #Ncommand, which is displayed in the window. To

    enable output in *"+lus, you must eplicitly issue the SET SERVER#UTPUT #N

    command.

    Step &7 0n this eample, a value is stored in the _fnamevariable. @owever, the value

    has not been printed. !se the PUT_LINEprocedure of the DB$S_#UTPUTpac%age to

    display the output. +ass the value that has to be printed as an argument to this

    procedure. The procedure then outputs the argument. 7lic% 4un Scriptto eecute theanonymous bloc%.

    Question

    2hich statements best describe the +"*" bloc% structure9

    Options-

    1. The declarative section is optional

    :. The ENDstatement represents the end of program eecution

    ;. The eception section is mandatory

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    14/61

    ption ! is correct. 2he declaration section contains declarations o' all varia"les&

    constants& cursors& and user-de'ined exceptions that are re'erenced in the

    executa"le and exception sections.

    ption ( is correct. 2he ENDstatement represents the end o' the PL/SQL

    executa"le section.

    ption + is incorrect. Exception "loc*s contain the actions to per'orm #hen errors

    and a"normal conditions arise in the executa"le section& "ut these actions are not

    re4uired.

    ption is incorrect. 2he BE'INstatement& not the DECLAREstatement&

    represents the "eginning o' the executa"le section. 5t can contain SQL statements

    to retrieve data 'rom the data"ase and PL/SQL statements to manipulate data in

    the "loc*.

    Question

    2hich statement accurately describes a +"*" bloc% type9

    Options-

    1. Anonymous bloc%s are unnamed bloc%s that only run at the time of eecution

    :. *tored procedures and functions provide the same functionality

    ;. *ubprograms are stored at the application level only

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    15/61

    Options-

    1. Output functionality must be enabled in *" Developer

    :. +"*" has built$in output functionality

    ;. 2hen using *"+lus, output is automatically enabled

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    16/61

    | &. PL/SQL bloc- structure|

    | Summar5|

    7opyright :EEF *%ill*oft. All rights reserved.*%ill*oft and the *%ill*oft logo are trademar%s or registered trademar%s

    of *%ill*oft in the !nited *tates and certain other countries.All other logos or trademar%s are the property of their respective owners.

    | Print| Contents| Close|

    Introducing PL/SQL :ariables

    Learning objective

    After completing this topic, you should be able to identify the steps for declaring and

    initializing PL!SQL variables

    1. Introducing variables

    2ith +"*", you can declare variables and then use them in *" and procedural

    statements. Kariables are mainly used for storage of data and manipulation of stored

    values.

    This sample +"*" statement retrieves the "IRST_NA$Eand DEPART$ENT_IDfrom

    the table. 0f you have to manipulate the "IRST_NA$Eor the DEPART$ENT_ID, then you

    have to store the retrieved value.

    SELECT

    first_name,

    department_id

    INT#

    _fname,

    _deptn%

    "R#$ 0

    Kariables are used to store values temporarily. 5ou can use the values stored in these

    variables for processing and manipulating data.

    Kariables can store any +"*" ob3ect, such as variables, types, cursors, and

    subprograms.

    Ceusability is another advantage of declaring variables. After the variables are declared,

    you can use them repeatedly in an application by referring to them multiple times in

    various statements.

    The re&uirements for variable names are that they

    http://library.skillport.com/courseware/cbtlib/257801/257804/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257801/257804/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20parent.window.close%28%29/http://library.skillport.com/courseware/cbtlib/257801/257804/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257801/257804/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/
  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    17/61

    must start with a letter

    can include letters or numbers

    can include special characters L such as M, N, and

    must contain no more than ;E characters

    must not include reserved words

    5ou can use variables in various ways-

    declare and initiali4e variables in the declaration section

    use variables and assign new values to them in the eecutable section

    pass variables as parameters to +"*" subprograms

    use variables to hold the output of a +"*" subprogram

    declare and initiali;e variables in te declaration section

    One way of using variables is to declare and initiali4e them in the declaration section. 5oucan declare variables in the declarative part of any +"*" bloc%, subprogram, or

    pac%age. Declarations allocate storage space for a value, specify its data type, and name

    the storage location so that you can reference it. Declarations can also assign an initial

    value and impose the N#T NULLconstraint on the variable. Borward references are not

    allowed. 5ou must declare a variable before referencing it in other statements, including

    other declarative statements.

    use variables and assign ne% values to tem in te eecutable section

    5ou can use variables and assign new values to them in the eecutable section. 0n this

    section, the eisting value of the variable can be replaced with the new value.

    pass variables as parameters to PL/SQL subprograms

    *ubprograms can ta%e parameters. 5ou can pass variables as parameters to

    subprograms.

    use variables to old te output o6 a PL/SQL subprogram

    5ou can use variables to hold the output of a +"*" subprogram that is returned by a

    function.

    Question

    2hich are true statements about variable name assignment9

    Options-

    1. Kariables may contain any number of characters as long as their length is defined

    :. Kariables may include special characters

    ;. Kariables may start with either letters or numbers, but not special characters

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    18/61

    $ns%er

    Kariables may include special characters and must not include reserved words.

    ption ! is incorrect. 7aria"les have a maximum length o' +8 characters. 2he

    varia"le can have its length assigned to it& "ut the name itsel' must "e +8characters or less.

    ption ( is correct. 7aria"les names may include letters& num"ers& and special

    characters.

    ption + is incorrect. 7aria"les names must al#ays "egin #ith a letter. 0um"ers

    or special characters are not permitted at the "eginning o' any varia"le name.

    ption is correct. 7aria"les may not use reserved #ords& such as $#DI"1& ADD&

    or ALL. 2hese #ords are reserved "y racle and have a speci'ic 'unction.

    &. Declaring and initiali;ing variables

    5ou must declare all +"*" identifiers in the declaration section before referencing them

    in the +"*" bloc%.

    This is the synta for declaring a +"*" identifier.

    identi'ierP7O?*TA?TQ datatypeP?OT ?!""Q

    P-R | DBA!"T exprQI

    0n the synta, you can specify certain elements.

    identifier

    C#NSTANT

    datatype

    N#T NULL

    expr

    identifier

    identifieris the name of the variable.

    CONSTANT

    C#NSTANTconstrains the variable so that its value cannot change. 7onstants must be

    initiali4ed.

    datatype

    datatypeis a scalar, composite, reference, or large ob3ect ("OG# data type.

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    19/61

    NOT NULL

    N#T NULLconstrains the variable so that it must contain a value. N#T NULLvariables

    must be initiali4ed.

    expr

    The expris any +"*" epression that can be a literal epression, another variable, oran epression involving operators and functions.

    5ou have the option of assigning an initial value to a variable. 5ou do not need to assign a

    value to a variable in order to declare it. 0f you refer to other variables in a declaration,

    you must be sure that they are already declared separately in a previous statement.

    This code shows some eamples of declaring variables.

    DECLARE

    _2iredate DATE&

    _deptn% NU$BER345 N#T NULL 67 -.&_%8ati%n VARCHAR43-95 67:Atanta:&

    8_8%mm C#NSTANT NU$BER 67 -;..&

    #ote

    5n addition to varia"les& you can declare cursors and exceptions in the declarative

    section.

    7onsider a sample code, in which a variable is declared in the declarative section but

    initiali4ed in the eecutable bloc% of the code bloc%.

    0n this code bloc%, the _m!Namevariable is declared in the declarative section of the

    bloc%. This variable can be accessed in the eecutable section of the same bloc%. A value

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    20/61

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    21/61

    following the notation is the delimiter used.

    5ou enter your string after specifying the delimiter, close the delimiter, and close the

    notation with a single &uotation mar%.

    _eent VARCHAR43-@567:"at2er::s da!:&

    _eent 67 :"at2er:s da!:&

    This sample code indicates the use of )as a delimiter.

    _eent 67 :)$%t2er:s da!*:&

    very +"*" variable has a data type, which specifies a storage format, constraints, and

    a valid range of values.

    +"*" supports these four data type categories, which you can use these data types to

    declare variables, constants, and pointers-

    scalar

    composite

    reference

    "OG

    scalar

    *calar data types hold a single value. The value depends on the data type of the variable.

    Bor eample, the _m!Namevariable in the code eample is of type VARCHAR4. Therefore,

    _m!Namecan hold a string value. +"*" also supports Goolean variables.

    composite

    7omposite data types contain internal elements that are either scalar or composite.

    REC#RDand TABLEare eamples of composite data types.

    re6erence

    Ceference data types hold values, called pointers, which point to a storage location.

    L8

    "OG data types hold values, called locators, which specify the location of large ob3ects L

    such as graphic images L that are stored outside the table.

    ?on$+"*" variables include host language variables declared in precompiler programs,

    screen fields in Borms applications, and host variables.

    @ere are eamples of different data types-

    TRUErepresents a Goolean value

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    22/61

    4@+

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    23/61

    )code=

    sa C#NSTANT NU$BER 67 @....=..&

    )code=

    initiali;e te variable to an epression

    0nitiali4e the variable to an epression with the assignment operator67

    or with the

    DE"AULTreserved word. 0f you do not assign an initial value, the new variable contains

    NULLby default until you assign a value. To assign or reassign a value to a variable, you

    write a +"*" assignment statement. 0t is good programming practice to initiali4e all

    variables.

    )code=

    _m!Name VARCHAR434.567:

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    24/61

    ?

    ).code=

    impose teNOT NULLconstraint

    0mpose the N#T NULLconstraint when the variable must contain a value. 0f you use the

    N#T NULLconstraint, you must assign a value when you declare the variable. 5ou cannot

    assign nulls to a variable defined as N#T NULL. The N#T NULLconstraint must be

    followed by an initiali4ation clause.

    )code=

    pin8%de VARCHAR43-@5 N#T NULL 67 :#Gf%rd:&

    )code=

    Question

    2hich statement about declaring and initiali4ing +"*" variables is true9

    Options-

    1. 7onstant variables cannot be changed

    :. 0dentifiers can be used without being declared in the declaration bloc%

    ;. Once declared, you must assign a value to a variable

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    25/61

    Options-

    1. Any character that appears before the delimiter is used in the string

    :. The first single &uotation mar% in a set of two acts as an escape character

    ;. The :notation is used to specify a delimiter

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    26/61

    | *op o6 page|

    | Learning objective|

    | 1. Introducing variables|

    | &. Declaring and initiali;ing variables|

    | Summar5|

    7opyright :EEF *%ill*oft. All rights reserved.*%ill*oft and the *%ill*oft logo are trademar%s or registered trademar%s

    of *%ill*oft in the !nited *tates and certain other countries.All other logos or trademar%s are the property of their respective owners.

    | Print| Contents| Close|

    Introducing PL/SQL Data *5pes and $ttributes

    Learning objective

    After completing this topic, you should be able to identify the uses of different PL!SQL

    data types, the #$%P& attribute, and '()D variables

    1. Using PL/SQL data t5pes

    +"*" provides a variety of predefined data types. Bor instance, you can choose from

    integer, floating point, character, Goolean, date, collection, and large ob3ects ("OG# types.

    A scalar data type holds a single value and has no internal components. *calar data

    types can be classified into four categories- number, character, date, and Goolean.

    7haracter and number data types have subtypes that associate a base type to a

    constraint. Bor eample, INTE'ERand P#SITIVEare subtypes of the NU$BERbase

    type.

    These are some basic scalar data types-

    CHAR )3maximum_length5*

    VARCHAR4 3maximum_length5

    NU$BER )3precision, scale5*

    BINAR1_INTE'ER

    PLS_INTE'ER

    B##LEAN

    BINAR1_"L#AT

    http://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20parent.window.close%28%29/http://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257801/257805/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/
  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    27/61

    BINAR1_D#UBLE

    CHAR [(maximum_length)]

    The CHARdata type is the base type for fied$length character data up to ;:,SS bytes. 0f

    you do not specify a maimum length, the default length is set to 1.

    VARCHAR2 (maximum_length)

    The VARCHAR4data type is the base type for variable$length character data up to ;:,SS

    bytes. There is no default si4e for VARCHAR4variables and constants.

    NUMBER [(precision, scale)]

    The NU$BERdata type represents a number having precision pand scale s. The precision

    pcan range from 1 through ;F. The scale scan range from $F< through 1:S.

    BINARY_INTEGER

    The BINAR1_INTE'ERdata type is the base type for integers between

    $:,1

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    28/61

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    29/61

    SEC#ND)3precision25*, where precision1and precision2specify the number of

    digits in the days field and seconds field, respectively. 0n both cases, you cannot use a

    symbolic constant or variable to specify the precisionL you must use an integer literal

    in the range E$V. The defaults are : and , respectively.

    The TI$ESTA$P FITH L#CAL TI$E #NEdata type differs from the TI$ESTA$PFITH TI$E #NEdata type in that when you insert a value into a database column, the

    value is normali4ed to the database time 4one, and the time$4one displacement is not

    stored in the column. 2hen you retrieve the value, the Oracle server returns the value in

    your local session time 4one.

    @ere are some eamples of variable declarations-

    _emp_%/

    _8%unt_%%p

    _dept_t%ta_sa

    _%rderdate

    8_taG_rate

    _aid

    v_!"_#$%

    _emp_%/is a variable to store an employee 3ob title.

    )code=

    DECLARE

    _emp_%/ VARCHAR43J5&

    )code=

    v_&$'_*$$"

    _8%unt_%%pis a variable to count the iterations of a loopI initiali4ed to ..

    )code=

    _8%unt_%%p BINAR1_INTE'ER 67 .&

    ?8%de

    v_+"_$*_-*

    _dept_t%ta_sais a variable to accumulate the total salary for a departmentI

    initiali4ed to ..

    )code=

    _dept_t%ta_sa NU$BER3J,45 67 .&

    ?8%de

    v_$.+.+

    _%rderdateis a variable to store the ship date of an orderI initiali4ed to one wee% from

    today.

    8%de

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    30/61

    _%rderdate DATE 67 S1SDATE M &

    ?8%de

    &_/_.

    8_taG_rateis a constant variable for the ta rate, which never changes throughout the

    +"*" bloc% set to=4@

    .

    8%de

    8_taG_rate C#NSTANT NU$BER39,45 67 =4@&

    ?8%de

    v_v*0+

    _aidis a flag to indicate whether a piece of data is valid or invalidI initiali4ed to TRUE.

    8%de

    _aid B##LEAN N#T NULL 67 TRUE&

    ===

    ?8%de

    +"*" variables are usually declared to hold and manipulate data stored in a database.

    2hen you declare +"*" variables to hold column values, you must ensure that the

    variable is of the correct data type and precision. 0f it is not, a +"*" error occurs during

    eecution. 0f you have to design large subprograms, this can be time consuming and error

    prone.

    Cather than hard coding the data type and precision of a variable, you can use the OT1PE

    attribute to declare a variable according to another previously declared variable or

    database column. The OT1PEattribute is most often used when the value stored in the

    variable is derived from a table in the database. 2hen you use the OT1PEattribute to

    declare a variable, you should prefi it with the database table and column name. 0f yourefer to a previously declared variable, prefi the variable name of the previously declared

    variable to the variable being declared.

    These are some advantages of the OT1PEattribute-

    helps avoid data type mismatch errors

    helps avoid data type hard coding

    ensures variable and column compatibility

    elps avoid data t5pe mismatc errors

    Gy using the OT1PEattribute, you can avoid errors caused by data type mismatch or

    wrong precision.

    elps avoid data t5pe ard coding

    Gy using the OT1PEattribute, you can avoid hard coding the data type of a variable.

    ensures variable and column compatibilit5

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    31/61

    The OT1PEattribute ensures compatibility of a variable with the column. !sing the OT1PE

    attribute, you need not change the variable declaration if the column definition changes. 0f

    you have already declared some variables for a particular table without using the OT1PE

    attribute, the +"*" bloc% may throw errors if the column for which the variable is

    declared is altered. 2hen you use the

    OT1PEattribute, +"*" determines the data type and si4e of the variable when the bloc%is compiled. This ensures that the variable is always compatible with the column that is

    used to populate it.

    This is the synta for declaring variables with the OT1PEattribute.

    identi'iertable.columnNnameWT5+I

    This sample code declares variables to store the last name of an employee. The

    emp_namevariable is defined to be of the same data type as the ast_namecolumn in

    the E$PL#1EEStable. The OT1PEattribute provides the data type of a database column.

    ===

    emp_name emp%!ees=ast_nameOT1PE&

    ===

    @ere is a sample code that declares variables to store the balance of a ban% account, as

    well as the minimum balance, which is 1,EEE. The min_/aan8evariable is defined to

    be of the same data type as the /aan8evariable. The OT1PEattribute provides the data

    type of a variable.

    ===

    /aan8e NU$BER3,45&min_/aan8e /aan8eOT1PE 67 -...&

    ===

    A N#T NULLdatabase column constraint does not apply to variables that are declared

    using OT1PE. Therefore, if you declare a variable using the OT1PEattribute that uses a

    database column defined as N#T NULL, you can assign the NULLvalue to the variable.

    2ith +"*", you can compare variables in both *" and procedural statements. These

    comparisons, called Goolean epressions, consist of simple or comple epressions

    separated by relational operators.

    0n a *" statement, you can use Goolean epressions to specify the rows in a table that

    are affected by the statement. 0n a procedural statement, Goolean epressions are the

    basis for conditional control. NULLstands for a missing, inapplicable, or un%nown value.

    2hen declaring Goolean variables

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    32/61

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    33/61

    ption is incorrect. PLS_INTE'ERis a "ase scalar type 'or signed integers

    "et#een -(&!>&@+&A> and (&!>&@+&A>.

    Question

    2hich are true statements about using B##LEANvariables9

    Options-

    1. B##LEANcan be used concurrently with conditional epressions

    :. B##LEANmay not be used concurrently with epressions performing arithmetic

    operations

    ;. B##LEANvalues may be reset after they have been set as a result of a comparison

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    34/61

    @owever, bind variables are accessible even after the bloc% is eecuted. Therefore, when

    created, bind variables can be used and manipulated by multiple subprograms. They can

    be used in *" statements and +"*" bloc%s 3ust li%e any other variable. These

    variables can be passed as run$time values into or out of +"*" subprograms.

    To create a bind variable in *" Developer, you use theVARIABLE

    command.

    Bor eample, you declare a variable of type NU$BERand VARCHAR4.

    VARIABLE return_8%de NU$BER

    VARIABLE return_ms VARCHAR439.5

    *" Developer can reference the bind variable and can display its value through the

    PRINTcommand. 5ou can reference a bind variable in a +"*" program by preceding

    the variable with a colon.

    VARIABLE /_resut NU$BERBE'IN

    SELECT 3SALAR1Q-45 M NVL3C#$$ISSI#N_PCT,.5 INT# 6/_resut

    "R#$ emp%!ees FHERE emp%!ee_id 7 -;;&

    END&

    ?

    PRINT /_resut

    /_resut

    ++++++++++

    9....

    #ote

    5' you are creating a "ind varia"le o' the NU$BERtype& you cannot speci'y the

    precision and scale. 6o#ever& you can speci'y the si9e 'or character strings. 3n

    racle NU$BERis stored in the same #ay regardless o' the dimension. 2he racle

    server uses the same num"er o' "ytes to store >& >8& and .8>+. 5t is not practical

    to calculate the si9e o' the racle num"er representation 'rom the num"er 'ormat&

    so the code al#ays allocates the "ytes needed. )ith character strings& the si9e is

    re4uired 'rom the user so that the re4uired num"er o' "ytes can "e allocated.

    0n *"+lus, you can display the value of a bind variable by using the PRINTcommand.

    2hen you eecute this +"*" bloc%, you get this output when the PRINTcommand

    eecutes.

    VARIABLE /_emp_saar! NU$BER

    BE'IN

    SELECT saar! INT# 6/_emp_saar!

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    35/61

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    36/61

    /_emp_saar!

    ++++++++++++++++++

    ...

    "OGs are meant to store a large amount of data. A database column can be of the "OG

    category.

    2ith the "OG category of data types, you can store bloc%s of unstructured data such as

    tet, graphic images, video clips, and sound wave forms, of up to 1:F terabytes

    depending on the database bloc% si4e. "OG data types allow efficient, random, and

    piecewise access to the data and can be attributes of an ob3ect type.

    These are some "OG data types-

    CL#B

    BL#B

    B"ILE

    NCL#B

    CLOB

    The character large ob3ect (CL#B# data type is used to store large bloc%s of character data

    in the database.

    BLOB

    The binary large ob3ect (BL#B# data type is used to store large unstructured or structured

    binary ob3ects in the database. 2hen you insert or retrieve such data into or from the

    database, the database does not interpret the data. ternal applications that use this datamust interpret the data.

    BFILE

    The binary file (B"ILE# data type is used to store large binary files. !nli%e other "OGs,

    B"ILESare not stored in the database. B"ILEsare stored outside the database. They

    could be operating system files. Only a pointer to the B"ILEis stored in the database.

    NCLOB

    The national language character large ob3ect (NCL#B# data type is used to store large

    bloc%s of single$byte or fied$width multibyte NCHAR!nicode data in the database.

    A scalar type has no internal components. A composite type has internal components that

    can be manipulated individually.

    7omposite data types, also %nown as collections, include TABLE, REC#RD, NESTED

    TABLE, and VARRA1types.

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    37/61

    5ou use the TABLEdata type to reference and manipulate collections of data as a whole

    ob3ect.

    5ou use the REC#RDdata type to treat related but dissimilar data as a logical unit.

    Question

    2hich statements describe the proper use of L#Bdata types9

    Options-

    1. B"ILEtypes are used to store large amounts of data within the actual database,

    such as video clips or movies

    :. BL#Btypes store large amounts of binary data, such as an image

    ;. CL#Btypes can store any sort of character data, including foreign languages and

    symbols

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    38/61

    can also compare variables in both *" and procedural statements using Goolean

    epressions.

    Gind variables are variables that you create in a host environment. To create a bind

    variable in *" Developer, you use the VARIABLEcommand. "OGs are meant to store a

    large amount of data and allow efficient, random, and piecewise access to the data andcan be attributes of an ob3ect type. *ome "OG data types include CL#B, BL#B, B"ILE,

    and NCL#B.

    *able o6 Contents

    | *op o6 page|

    | Learning objective|

    | 1. Using PL/SQL data t5pes|

    | &. Using bind variables and L8 data t5pes|

    | Summar5|

    7opyright :EEF *%ill*oft. All rights reserved.*%ill*oft and the *%ill*oft logo are trademar%s or registered trademar%s

    of *%ill*oft in the !nited *tates and certain other countries.All other logos or trademar%s are the property of their respective owners.

    | Print| Contents| Close|

    ,riting Eecutable StatementsLearning objective

    After completing this topic, you should be able to identify the steps for constructing

    eecutable statements using various PL!SQL bloc" elements

    1. Understanding leical units

    "eical units are building bloc%s of any +"*" bloc% and include letters, numerals,

    special characters, tabs, spaces, returns, and symbols. "eical units can be classified as

    identifiers

    delimiters

    literals

    comments

    http://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20parent.window.close%28%29/http://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257801/257806/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/
  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    39/61

    0dentifiers are the names given to +"*" ob3ects. uoted identifiers allow you to

    ma%e identifiers case sensitive

    include characters such as spaces

    use reserved words

    #ote

    Bey#ords cannot "e used as identi'iers.

    @ere are some eamples of &uoted identifiers. All subse&uent usage of these variables

    should have double &uotation mar%s. @owever, use of &uoted identifiers is not

    recommended.

    /ein date DATE&

    end date DATE&

    eG8epti%n t2r%n B##LEAN DE"AULT TRUE&

    Delimiters are simple or compound symbols that have special meaning in +"*".

    *emicolon (I# is an eample of a delimiter that is used to terminate a *" or +"*"

    statement. The tables display a list of simple and compound symbols.

    Supplement

    Selecting the lin* title opens the resource in a ne# "ro#ser #indo#.

    Launc %indo%

    Kiew the tables for simple symbols and compound symbols.

    #ote

    2he list o' sym"ols is only a su"set and not a complete list o' delimiters.

    A literal is any value that is assigned to a variable. A literal is an eplicit numeric,

    character string, date, or Goolean value that is not represented by an identifier.

    "iterals are classified as

    character literals

    numeric literals

    Goolean literals

    caracter literals

    http://dowindow%28%27misc/opsf0121_01.html');http://dowindow%28%27misc/opsf0121_01.html');
  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    40/61

    All string literals have the data type CHARor VARCHAR4and are therefore, called character

    literals. Bor eample

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    41/61

    you can format an unformatted *" statement by right$clic%ing the active *" wor%sheet and

    selecting the ormat SQL option in *" Developer

    &. Using SQL 6unctions and conversions

    *" provides several predefined functions that can be used in *" statements. 8ost of

    these functions are valid in +"*" epressions-

    single$row number and character functions

    data type conversion functions

    date and time$stamp functions

    These functions are not available in procedural statements-

    DEC#DE

    group functions such as AV', $IN, $A(, C#UNT, SU$, STDDEV, and VARIANCE

    6roup functions apply to groups of rows in a table and are, therefore, available only in

    *" statements in a +"*" bloc%. The functions mentioned here are only a subset of

    the complete list.

    5ou can use *" functions to manipulate data. These functions are grouped into these

    categories-

    number

    character conversion

    date

    miscellaneous

    0n this sample code, the LEN'TH*" function is used to get the length of a string.

    _des8_sie INTE'ER3@5&

    _pr%d_des8ripti%n VARCHAR43.567:1%u 8an use t2is

    pr%du8t it2 !%ur radi%s f%r 2i2er freuen8!:&

    ++ et t2e ent2 %f t2e strin in pr%d_des8ripti%n_des8_sie67 LEN'TH3pr%d_des8ripti%n5&

    0n this sample code, the $#NTHS_BETFEEN*" function is used to get the number of

    months an employee has wor%ed.

    _tenure67 $#NTHS_BETFEEN 3CURRENT_DATE, _2iredate5&

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    42/61

    0n Oracle Database 11g, you can use the NE(TVALand CURRVALpseudo$columns in any

    +"*" contet where an epression of NU$BERdata type may legally appear. Although

    the old style of using a SELECTstatement to &uery a se&uence is still valid, it is

    recommended that you do not use it.

    DECLARE_ne_id NU$BER&

    BE'IN

    _ne_id 67 m!_se=NE(TVAL&

    END&

    ?

    Gefore Oracle Database 11g, you were forced to write a *" statement in order to use a

    se&uence ob3ect value in a +"*" subroutine. Typically, you write a SELECTstatement

    to reference the pseudo$columns of NE(TVALand CURRVALto obtain a se&uence

    number. This method created a usability problem.

    DECLARE

    _ne_id NU$BER&

    BE'IN

    SELECT m!_se=NE(TVAL INT# _ne_id "R#$ Dua&

    END&

    ?

    0n Oracle Database 11g, the limitation of forcing you to write a *" statement to retrieve

    a se&uence value is lifted. 2ith the se&uence enhancement feature

    se&uence usability is improved less typing is re&uired by the developer

    the resulting code is clearer

    0n any programming language, converting one data type to another is a common

    re&uirement. Data type conversion involves converting data to comparable data types.

    +"*" can handle such conversions with scalar data types.

    Data type conversions can be of these two types-

    implicit

    eplicit

    implicit

    0n an implicit conversion, +"*" attempts to convert data types dynamically if they are

    mied in statement. 0mplicit conversions can be between

    characters and numbers

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    43/61

    characters and dates

    eplicit

    An eplicit conversion converts values from one data type to another using built$in

    functions. Bor eample, to convert a CHARvalue to a DATEor NU$BERvalue, use

    T#_DATEor T#_NU$BER, respectively.

    7onsider this sample code for implicit conversions. 0n this code, the sa_2ievariable is

    of the VARCHAR4type. 2hen calculating the total salary, +"*" first converts sa_2ie

    to NU$BERand then performs the operation. The result is of the NU$BERtype.

    DECLARE

    _saar! NU$BER3567...&

    _sa_2ie VARCHAR43@567:-...:&

    _t%ta_saar! _saar!OT1PE&

    BE'IN

    _t%ta_saar!67_saar! M _sa_2ie&

    END&

    @ere are three eamples of implicit and eplicit conversions of the DATEdata type.

    0n the first eample, because the string literal being assigned to date_%f_%ininis in

    the default format, this eample performs implicit conversion and assigns the specified

    date to date_%f_%inin.

    0n the second eample, +"*" returns an error because the date that is being assigned

    is not in the default format.

    0n the third eample, the T#_DATEfunction is used to eplicitly convert the given date in a

    particular format and assign it to the DATEdata type variable date_%f_%inin.

    ??EGampe -

    date_%f_%inin DATE67 :.4+"e/+4...:&

    ??EGampe 4

    date_%f_%inin DATE67 :"e/ruar! .4,4...:&

    ??EGampe 9

    date_%f_%inin DATE67 T#_DATE3:"e/ruar!

    .4,4...:,:$%nt2 DD, 1111:5&

    Question

    2hich are true statements about data type conversion in +"*"9

    Options-

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    44/61

    1. An eplicit conversion would be re&uired to convert a string to number format

    :. 7haracters can be converted to dates implicitly

    ;. 0mplicit conversions ta%e place when +"*" attempts to convert data types via the

    use of built$in functions

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    45/61

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    46/61

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    47/61

    DB$S_#UTPUT=PUT_LINE3:"at2er::s Name6 :>>_fat2er_name5&

    DB$S_#UTPUT=PUT_LINE3:Date %f Birt26 :

    >>%uter=_date_%f_/irt25&

    DB$S_#UTPUT=PUT_LINE3:C2id::s Name6 :>>_82id_name5&

    DB$S_#UTPUT=PUT_LINE3:Date %f Birt26 :>>_date_%f_/irt25&

    END&

    END&

    END %uter&

    This is the output of running the previous nested bloc% code eample.

    ++ #utput

    an%n!m%us /%8 8%mpeted

    "at2er:s Name6 Patri8

    Date %f Birt26 4.+Apr+4

    C2id:s Name6 $ie

    Date %f Birt26 -4+De8+.4

    The operations in an epression are performed in a particular order depending on their

    precedence or priority. *ome operators in +"*", as in *" include

    logical

    arithmetic

    concatenation

    parentheses to control order of operations

    eponential operator

    @ere is a table that shows the default order of operations from high priority to low priority.

    Supplement

    Selecting the lin* title opens the resource in a ne# "ro#ser #indo#.

    Launc %indo%

    Kiew the table for the default order of operations from high priority to low priority.

    @ere are some eamples of using operators in +"*"-

    1. the Marithemetic operator is used to increment the counter for a loop

    :. the ANDlogical operator and the BETFEENcomparison operator are used to set the

    value of a Goolean flag

    http://dowindow%28%27misc/opsf0121_03.html');http://dowindow%28%27misc/opsf0121_03.html');
  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    48/61

    ;. the IS N#T NULLcomparsion operator is used to validate whether an employee

    number contains a value

    ??EGampe -

    %%p_8%unt 67 %%p_8%unt M -&

    ??EGampe 4

    %%d_sa 67 sa BETFEEN @.... AND -@....&

    ??EGampe 9

    aid 67 3empn% IS N#T NULL5&

    2hen wor%ing with nulls, you can avoid some common mista%es by %eeping in mind

    these rules-

    comparisons involving nulls always yield NULL

    applying the logical operator N#Tto a null yields NULL

    in conditional control statements, if the condition yields NULL, its associated se&uence of

    statements is not eecuted

    To produce clear code and reduce maintenance when developing a +"*" bloc%, you

    need to consider

    code conventions

    indentation of code

    This table provides guidelines for writing code in uppercase or lowercase characters tohelp distinguish %eywords from named ob3ects.

    Supplement

    Selecting the lin* title opens the resource in a ne# "ro#ser #indo#.

    Launc %indo%

    Kiew the table for guidelines for writing code in uppercase or lowercase

    characters.

    Bor clarity and enhanced readability, you should indent each level of code. To show

    structure, you can divide lines by using carriage returns and you can indent lines by using

    spaces and tabs.

    ??EGampe -

    BE'IN

    I" G7. THEN

    http://dowindow%28%27misc/opsf0121_02.html');http://dowindow%28%27misc/opsf0121_02.html');
  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    49/61

    !67-&

    END I"&

    END&

    ?

    ??EGampe 4

    DECLARE

    deptn% NU$BER3;5&

    %8ati%n_id NU$BER3;5&

    BE'IN

    SELECT department_id,

    %8ati%n_id

    INT# deptn%,

    %8ati%n_id

    "R#$ departments

    FHERE department_name

    7 :Saes:&

    ===

    END&

    ?

    7onsider these two I"statements for readability.

    I" G! THEN maG67G&ELSE maG67!&END I"&

    I" G ! THEN

    maG 67 G&

    ELSE

    maG 67 !&END I"&

    Question

    2hich statements best describe the functionality of nested bloc%s9

    Options-

    1. ception sections may not contain nested bloc%s

    :. +"*" first loo%s to the inner bloc% for a given variable name when it is being

    accessed in the inner bloc%

    ;. Kariables declared in a +"*" bloc% are considered global to all bloc%s

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    50/61

    5ou can nest bloc%s wherever an eecutable statement is allowed. +"*" first

    loo%s to the inner bloc% for a given variable name when it is being accessed in the

    inner bloc%.

    ption ! is incorrect. %ou can nest "loc*s #herever an executa"le statement is

    allo#ed& and the exception section can also contain nested "loc*s.

    ption ( is correct. )hen you access a given varia"le in the inner "loc*& PL/SQL

    'irst loo*s 'or a local varia"le in the inner "loc* #ith that name. 5' there is no

    varia"le #ith the same name in the inner "loc*& PL/SQL loo*s 'or the varia"le in

    the outer "loc*.

    ption + is incorrect. 7aria"les declared in a PL/SQL "loc* are considered local to

    that "loc* and glo"al to all its su" "loc*s.

    ption is correct. %ou can nest "loc*s #herever an executa"le statement is

    allo#ed& thus ma*ing the nested "loc* a statement. 5' your executa"le section has

    code 'or much logically related 'unctionality to support multiple "usiness

    re4uirements& you can divide the executa"le section into smaller "loc*s.

    Question

    0dentify the best practices in +"*" programming that are used to improve code

    clarity and readability.

    Options-

    1. 7ode should not be indented

    :. Database and column names should be in lower case

    ;. Data types should be declared in upper case

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    51/61

    ption + is correct. Data types should al#ays "e in upper case. 1or example&

    VARCHAR4and B##LEANare declared in upper case.

    ption is incorrect. PL/SQL *ey #ords such as DECLARE& BE'IN& and I"should

    al#ays "e in upper case.

    Summar5

    "eical units are building bloc%s of any +"*". 0t includes identifiers, delimiters, literals,

    and comments. 0dentifiers are the names given to +"*" ob3ects. Delimiters are

    symbols that have special meaning in +"*". A literal is any value that is assigned to a

    variable. 7omments indicate that instructions need not be compiled.

    *" provides the single$row number and character, data type conversion, and date and

    time$stamp functions. The DEC#DEand group functions are not available in procedural

    statements. 7onversion functions convert a value from one data type to another and can

    be implicit and eplicit conversion.

    +"*" enables you to nest statements wherever an eecutable statement is allowed,

    thus ma%ing the nested bloc% a statement. 5ou can use comparison operators to

    compare one epression to another. The result is always TRUE, "ALSE, or NULL.

    *able o6 Contents

    | *op o6 page|

    | Learning objective|

    | 1. Understanding leical units|

    | &. Using SQL 6unctions and conversions|

    | '. Using nested bloc-s and operators|

    | Summar5|

    7opyright :EEF *%ill*oft. All rights reserved.*%ill*oft and the *%ill*oft logo are trademar%s or registered trademar%s

    of *%ill*oft in the !nited *tates and certain other countries.All other logos or trademar%s are the property of their respective owners.

    | Print| Contents| Close|

    ,or-ing %it Eecutable Statements

    Learning objective

    http://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#section_3http://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#section_3http://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257801/257809/eng/consim/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20parent.window.close%28%29/http://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#section_3http://library.skillport.com/courseware/cbtlib/257801/257808/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257801/257809/eng/consim/transcript.html#contentshttp://%20parent.window.close%28%29/
  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    52/61

    After completing this topic, you should be able to evaluate a bloc" of PL!SQL code +ith

    respect to scoping and nesting rules, and +rite and test PL!SQL bloc"s

    Eercise overvie%

    0n this eercise, you are re&uired to evaluate a bloc% of +"*" code and determine the

    data type and value of the specified variables. 5ou are also re&uired to identify the correct

    code segments to meet specified re&uirements.

    This involves the following tas%s-

    evaluating bloc% scoping rules

    evaluating bloc% nesting rules

    adding code for specific output

    5ou are a database administrator for a company. As a part of your responsibilities, youare re&uired to retrieve and manipulate the data in the relational databases of the

    company.

    *as- 17 Evaluating bloc- scoping rules

    One of your team members has written a +"*" code bloc% that trac%s the availability of

    products in different locations of the company.

    5ou need to evaluate this +"*" bloc% to determine the data types and values of

    variables according to the rules of scoping.

    DECLARE

    _ei2t NU$BER395 67 ..&

    _messae VARCHAR434@@5 67 :Pr%du8t -..-4:&

    BE'IN

    DECLARE

    _ei2t NU$BER395 67 -&

    _messae VARCHAR434@@5 67 :Pr%du8t --..-:&

    _ne_%8n [email protected] 67 :Eur%pe:&

    BE'IN

    _ei2t 67 _ei2t M -& _ne_%8n 67 :Festern : >> _ne_%8n&

    END&

    _ei2t 67 _ei2t M -&

    _messae 67 _messae >> : is in st%8:&

    _ne_%8n 67 :Festern : >> _ne_%8n&

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    53/61

    END&

    ?

    Supplement

    Selecting the lin* title opens the resource in a ne# "ro#ser #indo#.

    Launc %indo%

    Kiew this +"*" bloc% of code to answer the upcoming &uestions.

    Step 1 o6 '

    0dentify the value and data type of the V_FEI'HTvariable at position 1 of the

    provided code.

    Options-

    1. The value is 4and the data type is NU$BER

    :. The value is 4and the data type is VARCHAR4

    ;. The value is ;and the data type is NU$BER

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    54/61

    0dentify the value and data type of the V_NEF_L#CNvariable at position 1 of the

    provided code.

    Options-

    1. The value isEur%pe

    and the data type isVARCHAR4

    :. The value is is in st%8and the data type is VARCHAR4

    ;. The value is Pr%du8t --..-and the data type is VARCHAR4

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    55/61

    The value of the V_FEI'HTvariable at position : of the provided code is .-and

    its data type is NU$BER.

    ption ! is correct. 2he varia"le V_FEI'HTis declared #ith a NU$BERdata type

    and is initiali9ed #ith a value o' ... :y position ( o' the provided code& -has

    "een added to the value o' V_FEI'HTso that the value is .-.

    ption ( is incorrect. 2he varia"le V_FEI'HTis declared #ith a NU$BERdata

    type. 5ts initial value is ..& and "y position ( o' the provided code& its value is

    .-. 3t no point in the provided code is the value o' the V_FEI'HTvaria"le

    -..-4.

    ption + is incorrect. 2he V_FEI'HTvaria"le is declared #ith a NU$BERdata

    type. 2here'ore& Eur%peas a value #ould not "e accepta"le.

    ption is incorrect. 2he V_FEI'HTvaria"le is declared #ith a NU$BERdata

    type. 2here'ore& Festern Eur%peas a value #ould not "e accepta"le.

    *as- &7 Evaluating bloc- nesting rules

    One of your team members has written a +"*" code bloc% that retrieves the credit

    rating of different customers of the company.

    5ou need to evaluate this +"*" bloc% to determine the data types and values of

    variables.

    DECLARE _8ust%mer [email protected] 67 :F%mansp%rt:&

    _8redit_ratin [email protected] 67 :E(CELLENT:&

    BE'IN

    DECLARE

    _8ust%mer NU$BER35 67 4.-&

    _name VARCHAR434@5 67 :Unisp%rts:&

    BE'IN

    _8redit_ratin 67:'##D:&

    0

    END&

    0END&

    Supplement

    Selecting the lin* title opens the resource in a ne# "ro#ser #indo#.

    Launc %indo%

    http://dowindow%28%27misc/opsf0122_02.html');http://dowindow%28%27misc/opsf0122_02.html');
  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    56/61

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    57/61

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    58/61

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    59/61

    2hich code segment should you add to the eecutable section of the provided

    +"*" bloc%9

    Options-

    1. SELECT first_name, saar! IN _fname, _emp_sa "R#$ emp%!ees

    FHERE emp%!ee_id7--.&

    :. SELECT first_name, saar! INT# _fname, _emp_sa "R#$

    emp%!ees FHERE emp%!ee_id7--.&

    ;. SELECT first_name, saar! INT# _fname, _emp_sa "R#$

    emp%!ees&

    > first_name5&

    :. DB$S_#UTPUT=PUT_LINE3: He% : >> _fname5&

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    60/61

    ;. DB$S_#UTPUT=PUT_LINE3He% >> _fname5&

    > _fname5&

    4esult

    5ou should use this line of code-DB$S_#UTPUT=PUT_LINE3: He% : >> _fname5&=

    ption ! is incorrect. 5n this case& the call to the PUT_LINEprocedure o' the

    DB$S_#UTPUTpac*age re4uires the name o' the varia"le and not the name o' the

    column.

    ption ( is correct. 2his line o' code #ould result in output o' He%

  • 8/10/2019 Oracle Database 11g PLSQL Variables Attributes and Executable Statements

    61/61