SlideShare a Scribd company logo
1 of 25
Introduction to PL/SQL15




                                                    Chapter 1




                               Introduction to PL/SQL

                                                     Need for PL/SQL
                                             Benefits of Using PL/SQL
                                  PL/SQL Block Types and Constructs
                                              PL/SQL Block Structure
                               Operators and SQL Functions in PL/SQL
                                                             Variables
                                                        Nested Blocks




© SQL Star International Ltd                                           1
Introduction to PL/SQL15




Objectives

At the end of this chapter, you will be able to:

     State the need for a procedural language in Oracle

     Create PL/SQL blocks

     Write nested blocks




© SQL Star International Ltd                                             2
Introduction to PL/SQL15




Introducing PL/SQL
In the journey so far, you have learnt about the Structured Query Language (SQL).
The Oracle software provides a language, Procedural Language/SQL (PL/SQL), which
is an extension of SQL.

PL/SQL implements modularity in the codes you write. It allows you to perform
iterations and handle errors. Features like data hiding and error handling make
PL/SQL a state-of-the-art language for databases.

PL/SQL also allows data manipulation and SQL query statements to be included
within procedural units of code. This makes PL/SQL a powerful transaction processing
mechanism.


Need for PL/SQL
The requirement for PL/SQL was mainly due to the need to centralize automated
business tasks. For example, if each employee in an organization maintains separate
programs to manage their tasks and updates them at their discretion, it could create
confusions, such as:

   •   New employees or existing employees who are handed over someone else’s
             work, would have a problem understanding the process followed by
       the employee vis-à-vis the organization

   •   Any change in business policy or functionality would have to be updated by all
       the employees individually in all relevant programs.

In a centralized functionality this is avoided because all changes need to be made at
one place. Changes will get reflected in the relevant codes and all users can access
updated information.



Benefits of Using PL/SQL
The reasons for using PL/SQL are as follows:


    Integrating with the Oracle server and Oracle development tools
    Implementing performance enhancements in an application
    Modularizing the development of programs
    Implementing Portability
    Declaration of variables
    Programming with procedural language control structures
    Handling errors




© SQL Star International Ltd                                                       3
Introduction to PL/SQL15




Integration

PL/SQL plays a key role in:

    Oracle server, through stored procedures and functions, database triggers and
      packages
    Oracle development tools, through Oracle Developer component triggers

PL/SQL supports the use of SQL datatypes. With direct access provided by SQL,
these shared datatypes integrate PL/SQL with the Oracle server data dictionary.
Hence, PL/SQL successfully bridges the gap between access to database technology
and the need for procedural language capabilities.

Most applications such as Oracle Forms, Oracle Reports and Oracle Graphics, use
shared libraries (that hold code), which can be accessed locally or remotely. To
execute these stored codes, the Oracle tools have their own PL/SQL engine
(independent of the engine present in the Oracle server). The engine first filters out
the SQL statements to send them individually to the SQL statement executor in the
Oracle server. It then processes the remaining procedural statements in the
procedural statement executor in the PL/SQL engine. The procedural statement
executor processes data, which is already inside the client environment and not in
the database. This reduces the workload on the Oracle server and also the amount of
memory required.


Performance Enhancements of Applications
When SQL statements are sent to the Oracle server one at a time, each statement
results in a call to the Oracle server, leading to performance overhead and network
traffic. If your application is SQL intensive, then instead of sending SQL statements
individually to the server, you can put them into one block using PL/SQL and send
the entire block to the server at one time. This reduces network traffic.

PL/SQL also operates with Oracle development tools, thereby adding procedural
processing power to these tools and enhancing performance.




© SQL Star International Ltd                                                        4
Introduction to PL/SQL15




Modularized Program Development
PL/SQL programs are made up of one or more blocks. These blocks may be
individual ones or may be nested within another. That is, a block may represent a
small part of another block, which may in turn be part of a whole unit of code. The
units (procedures, functions or anonymous blocks) making up a PL/SQL program are
called logical blocks.


A diagrammatic representation of modularization is:




The advantages associated with modularized development of programs are:


    Logical groupings of related statements within blocks
    Nesting blocks within larger blocks help build powerful programs
    Breaking down complex problems into manageable sets of logical, well-defined
      modules, which can be implemented within blocks



Portability
PL/SQL is portable. That means, PL/SQL programs can be run wherever the Oracle
server exists. There is no need to tailor them to suit each new environment. This is
achieved because PL/SQL is native to the Oracle server, and therefore can be moved
to any environment (operating system or platform) that supports the Oracle server.

PL/SQL code can also be moved between the Oracle server and Oracle Developer
applications by writing programs and creating libraries in different environments.




© SQL Star International Ltd                                                       5
Introduction to PL/SQL15




Variable Declaration

In PL/SQL, you can declare variables:


    To use them in SQL and procedural statements
    Belonging to different data types
    Dynamically based on the structure of tables and columns in the database




Programming with Procedural Language Control Structures
PL/SQL allows the usage of control structures, which enable you to execute:

    Sequence of statements conditionally
    Sequence of statements iteratively in a loop
    Individually the rows returned by multiple-row query

Handling Errors
PL/SQL implements error handling functionality by:

    Processing Oracle server errors with error handling routines
    Declaring your own error conditions and process them with error handlers


PL/SQL Block Types and Constructs
There are two block types and different types of constructs in PL/SQL. A block is a
PL/SQL code. A construct is the way in which a block is written to implement
different functionality.

Block Types
Logical blocks are the basic units of code that make up a PL/SQL program. The two
kinds of PL/SQL blocks are:

    Anonymous blocks
    Named blocks or Subprograms

Anonymous Blocks
Anonymous blocks are declared at that point in an application from where they are
to be executed and are passed to the PL/SQL engine for execution at runtime. These
blocks are unnamed blocks. They can be embedded in the iSQL*Plus environment.
An application trigger consists of these blocks.

Subprograms
Unlike anonymous blocks, named blocks or subprograms are given a name. These
blocks can be invoked for execution and they can also accept parameters.



© SQL Star International Ltd                                                      6
Introduction to PL/SQL15



Subprograms can be declared as Procedures or Functions. You declare a subprogram
as a Procedure to perform an action, and you declare a subprogram as a Function to
compute a value. Subprograms can be written and stored either at the server side or
at the client side.

Constructs
There are various PL/SQL program constructs available that use the basic PL/SQL
block. The availability of program constructs depends on the environment in which
they are executed.




The different program constructs are given below.




© SQL Star International Ltd                                                     7
Introduction to PL/SQL15




PL/SQL Block Structure
To write a PL/SQL block, you need to know the different parts of a PL/SQL block and
what each part should hold. The structure of all PL/SQL blocks is the same. The only
difference is that, if it is an anonymous block it is not given a name.

A PL/SQL block has three sections . They are :

    Declarative section
    Executable section
    Exception handling section

The declarative section is where the variables and constants used in the body of the
block are declared. Any cursors or user-defined error handlers that are used in the
body are declared here. This section is optional.

The executable section holds the set of statements or the logic of the tasks that are
to be performed. You can include SQL statements to make changes to the database
and PL/SQL statements to manipulate data in the block. The statements in this block
are enclosed within the keywords BEGIN and END. This section is mandatory.

The last section of a block is the exception section. Here a set of statements is
written to handle any errors that might occur when the statements in the executable
section are being executed. This section is optional .




© SQL Star International Ltd                                                       8
Introduction to PL/SQL15




The diagramatic expression of PL/SQL block structure is given below.




The syntax for writing a PL/SQL block is:

        DECLARE
              <variable name> datatype(size);
        BEGIN
              SQL statements;
              PL/SQL statements;

              EXCEPTION
              WHEN <exception name> THEN
              …
      END;
      /
Some points that will help you write a block:

        A line of PL/SQL text which contains group of characters known as lexical
        units. These units are classified as follows:

    Delimiters are simple or compound symbols that have a special meaning to
     PL/SQL. The following table presents both the simple as well as the compound
     symbols:




© SQL Star International Ltd                                                     9
Introduction to PL/SQL15




    Identifiers are used to name PL/SQL program constructs such as Constants,
     Variables and Exceptions. The following points need to be kept in mind while
     using identifiers:

          •   Identifiers can be up to 30 characters in length, but ensure they start
              with an alphabet.

          •   Do not give the same name for the identifiers as the name of columns
              in a table used in the block. If so, then the Oracle server assumes that
              the table column is being referred.

          •   An identifier consists of a letter, followed (optional) by other letters,
              numerals, underscores, dollar signs and number signs. The following
              characters are however illegal:
                 Abc&efg – illegal ampersand
                 Abc-efg – illegal hyphen
                 Abc/efg – illegal slash
                 Abc efg – illegal space

          •   Identifiers should not be reserved words except when they are used
              within double quotes, for instance “INSERT”.

    Literals are made up of definite values such as character, numeric, string or
     Boolean values, not represented by identifiers. These are case sensitive.




© SQL Star International Ltd                                                        10
Introduction to PL/SQL15


Literals are of two types:

            •   Character literals: are all the printable characters such as letters,
                numerals, spaces, and special symbols. Specify character literals in
                single quotes.

            •   Numeric literals: are represented either by a simple value such as –12
                or by a scientific notation such as 3E6.

   Comments are extra information given by the programmer to improve
     readability                                      in a code, to enable
     documenting in each phase and debugging.
           PL/SQL code can be commented in two ways:
                •   Single line comment represented by --
                •   Multi line comment represented by /*      */



     Use a semicolon (;) at the end of all SQL and PL/SQL control statements and
      the
         END keyword.
     Do not use semicolons after the keywords DECLARE, BEGIN and EXCEPTION.
     Increase the readability of the block by writing the keywords in uppercase.
        Use a slash (/) to terminate a PL/SQL block on a line by itself.



Using Quotes in Literals
Oracle 10g allows you to define your own string delimiters to remove the need to
double up any single quotes.

        SET SERVEROUTPUT ON

        BEGIN

                --original code

                            DBMS_OUTPUT.PUT_LINE(‘He is New Jersey Library
                ‘’s Member!’);

                -- using quote symbol

                     DBMS_OUTPUT.PUT_LINE(q’# He is New Jersey
     Library‘s                    Member!#’);
            DBMS_OUTPUT.PUT_LINE(q’[ He is New Jersey
     Library‘s


© SQL Star International Ltd                                                        11
Introduction to PL/SQL15


                 Member !]’);

       END;
       /

       He is New Jersey Library‘s Member!
       He is New Jersey Library‘s Member!
       He is New Jersey Library‘s Member !

        PL/SQL procedure successfully completed

Operators in PL/SQL
The following operators are supported in PL/SQL:
    Arithmetic
    Logical
    Relational or Comparison
    Concatenation
    Exponentiation [Represented by (**)]


SQL Functions in PL/SQL Statements
All the SQL functions can also be used in procedural statements in a block.

These include:
             Single-row number and character functions
       Datatype conversion functions
       Date functions
             Timestamp functions
             GREATEST and LEAST functions

The functions that cannot be used in procedural statements are:

       DECODE
              Group functions like AVG, MIN, MAX, COUNT, SUM, STDDEV and
        VARIANCE. These functions work only on a group of rows in a table and
        hence, they can be used only with the SQL statements in a PL/SQL block.


Variables
A variable are named memory locations used to store data temporarily. The data
stored in variables is used in the blocks and then processed. When the processing is
completed, the data held in the variables may be written to the database or simply
erased in case of session wide variables.

Why is a Variable used?
A Variable stores data temporarily. It manipulates the stored data and performs
calculations with the data without accessing the database. Once declared, variables




© SQL Star International Ltd                                                     12
Introduction to PL/SQL15


can be used repeatedly in an application by referencing them in other statements in
the block.

When variables are declared using %TYPE and %ROWTYPE (more information is
provided later in the chapter), you are infact basing the variable declaration on the
column definition of a table. In this case, if the column definition changes, then the
variable declarations also changes accordingly. This helps in data independence,
reduces maintenance cost and allows the program to adjust to the new business
logic.

How to handle variables in PL/SQL?
In a PL/SQL block, variables are:

      Declared and initialized in the declarative section of the block.
      Assigned new values in the executable section. On doing so, the existing
       value is replaced with the newly assigned value. Care must be taken to see
       that a variable being referred to is already declared in the declarative section.
       Forward references cannot be made.

Types of Variables
Variables are of two types. They are:

      PL/SQL variables
      Non-PL/SQL variables

PL/SQL Variables
PL/SQL variables have a data type that specifies a storage format, constraints and
also valid range of values.
The data types used to declare PL/SQL variables are:

    Scalar data types are those that correspond to database column types. These
     data types hold only a single value. The base scalar data types include:

           CHAR
           VARCHAR2
           LONG
           LONG RAW
           NUMBER
           BINARY_INTEGER
           PLS_INTEGER
           BINARY_FLOAT
           BINARY_DOUBLE
             BOOLEAN
             DATE
             TIMESTAMP
             TIMESTAMP WITH TIMEZONE
             TIMESTAMP WITH LOCAL TIMEZONE
             INTERVAL YEAR TO MONTH
             INTERVAL DAY TO SECOND


© SQL Star International Ltd                                                         13
Introduction to PL/SQL15


Binary_Float and Binary_Double are the two new Datatypes introduced in
Oracle10g.They represent floating point numbers in IEEE 754 format (Institute of
Electrical and Electronic Engineers) and require 5 byte and 9 bytes to store the
values respectively. IEEE format s supported by most of the computer system
operating through native processor instructions thereby helping us to carry out
complex computations using floating point data.


 Composite data types are those that are defined by users. They enable you to
                  manipulate groups of data in PL/SQL blocks

 Reference data types are those that hold values pointing to other objects.
     These are also known as pointers.

 LOB (large object) data types: are those that hold values, which specify the
location of large objects such as graphic images. These values are known as locators.
Large objects are stored in the same database as the table but not within the table.
LOB data type allows you to store unstructured data of a maximum of 8-128
terabytes. This data could be a movie clip or a graphic image or a sound wave form.
LOBs are further classified into:

      CLOB (Character Large Objects) is used to store large blocks of character
     data of a single byte.
      BLOB (Binary Large Object) is used to store large binary objects within the
     database.
    BFILE (Binary File) is used to store large binary objects that are in the
      operating system files outside the database.
    NCLOB (National Language Character Large Objects), are used to store large
         blocks of NCHAR data that may be single-byte or fixed-width multiple bytes

The syntax for declaring PL/SQL variables is:

       identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];

Where,

identifier is the name assigned to the variable declared.

CONSTANT specifies a constraint that the value of the variable cannot change.
Constant variables must be initialized. While declaring a variable as a constant, the
CONSTANT keyword must precede the datatype specification.

DATATYPE specifies the type of data the variable can hold. It could be scalar,
composite, reference or LOB datatype.

NOT NULL specifies a constraint that the variable must contain a value. Therefore,
NOT NULL variables must be initialized.

:= is the assignment operator used to assign an expression to a variable. Instead of
the assignment operator, the DEFAULT expr (expression) can be used to assign
values to the variables.



© SQL Star International Ltd                                                      14
Introduction to PL/SQL15



By default, all variables are initialized to NULL. To prevent null values, variables are
initialized using the DEFAULT keyword.


The following code snippet shows how PL/SQL variables are declared in the
declarative section of a block:
       DECLARE
              FirstName CHAR(20);
              BranchID CHAR(7) NOT NULL: = ‘09RANNJ’;
              FeeAmt CONSTANT NUMBER(2): = 15;
              CatgName CHAR(15) DEFAULT ‘Fiction’;

% TYPE Attribute
If you need to store a database column value in a variable or write a value from a
variable to a database column, then the data type of the variable needs to be the
same as that of the database column. You can use the %TYPE attribute to declare a
variable to be of the same data type as that of a previously declared variable or
database column.

Incorrect variable data types generate PL/SQL errors during execution. When you
want to declare a variable using a table attribute instead of the datatype the syntax
is

              <variable_name> table.columnname%TYPE

For example, in case you want to declare a variable that will store the address of a
library member, you will write in the following syntax:

       DECLARE
             Address VARCHAR2(45);

But, the above declaration will result in an error when an attempt is made to
populate the variable with address details of members from the database table. This
is because there is a mismatch in type specification of the variable. The datatype
width of the vAddress column in table Member is 50, but you have declared it as
45. To overcome this, declare the variable using %TYPE attribute as follows:

       DECLARE
             Address Member.vAddress%TYPE;

This statement declares a variable whose datatype and width is based on the
vAddress column.

If you want to declare a variable of the same type as a previously declared variable
then the syntax is

              <variable_name> variable_name%TYPE




© SQL Star International Ltd                                                         15
Introduction to PL/SQL15


Using %TYPE attribute to declare a variable based on a previously declared variable,
is illustrated in the section dealing with the iSQL*Plus variables within PL/SQL blocks.
Datatype and Variable size is determined when the block is compiled. So even if
there is a change in the database column datatype the code manages the changed
datatype information.




Data Conversion Functions
In any programming language generally, we have to deal with different datatypes
simultaneously or receive data which is not in the default format. In such cases,
Oracle server implicitly converts data into valid datatypes wherever feasible. Explicit
conversions come into the scenario where automatic conversions are not possible.

Oracle Server takes care of implicit conversion between
1. Character and Number
2. Character and Date

But how is it done? Let us take an example.

      DECLARE
            cons_nfine NUMBER(3):=50;
            cons_extra_fine VARCHAR2(20):=’5';
            tot_fine Transaction.nfine%TYPE;
      BEGIN
            tot_fine:= cons_nfine+cons_extra_fine;
            DBMS_OUTPUT.PUT_LINE(‘The total fine                payable    is   Rs.‘||
tot_fine);
      END;
      /

So, did you notice something?
Variable cons_nfine is of number datatype and cons_extra_fine is of VARCHAR2
datatype. While assigning the result to tot_fine variable, cons_extra_fine is
converted to number by PL/SQL executer and then the operation is performed.




© SQL Star International Ltd                                                         16
Introduction to PL/SQL15




To perform explicit conversion, following built in functions can be used.
       to_char()
       to_number()
       to_date()
       to_Binary_float()
       to_Binary_double()


      DECLARE
            v_Date date:= to_Date( ‘April 04 2007’,’Month dd YYYY’);
      BEGIN
            DBMS_OUTPUT.PUT_LINE(‘You have entered   ‘ ||v_Date ||’ as
input’);
      END;
      /

Example to show the usage of new datatypes.

       DECLARE
               l_binary_float       BINARY_FLOAT;
               l_binary_double      BINARY_DOUBLE;
       BEGIN
               l_binary_float := 2.1f;
               l_binary_double := 2.00001d;
               DBMS_OUTPUT.PUT_LINE(l_binary_double);
               DBMS_OUTPUT.PUT_LINE(l_binary_float);
               l_binary_float := TO_BINARY_FLOAT(2.1);
               l_binary_double := TO_BINARY_DOUBLE(2.00001);
               DBMS_OUTPUT.PUT_LINE(l_binary_double);
               DBMS_OUTPUT.PUT_LINE(l_binary_float);
       END;
       /




© SQL Star International Ltd                                                      17
Introduction to PL/SQL15




Non-PL/SQL Variables
Since PL/SQL has neither input nor output capabilities, it relies on the environment in
which it is executed in order to pass values into and out of a PL/SQL block.

The following non-PL/SQL variables can be used within PL/SQL blocks:

      Substitution variables
      Host variables

Substitution variables are those that you can use to pass values to a PL/SQL block at
runtime. To reference a substitution variable in a block, prefix it with an ampersand
(&). Before the block is executed the values for the variables are substituted with the
values passed.

Hence, you cannot input different values for the substitution variables using a loop.
The substitution variable can be replaced only by one value.
Here is an example showing the use of substitution variables within PL/SQL blocks.
Suppose, the library wants to calculate its quarterly income based on its annual
income. To do this, it declares a substitution variable, which would prompt the user
to enter the figure of annual income. Based on the value entered, the quarterly
income would be calculated.

       DECLARE
             AnnualIncome NUMBER (7): = &annualinc;
             QuarterlyInc AnnualIncome%TYPE;
             -—declaring variable based on previously declared variable
       using             --%TYPE attribute.
       BEGIN
             QuarterlyInc:= AnnualIncome/4;
             DBMS_OUTPUT.PUT_LINE (‘The quarterly income of the library
       is:         ’|| QuarterlyInc);
       END;
       /

In the above block, to display the quarterly income calculated, you can specify the
DBMS_OUTPUT.PUT_LINE in the PL/SQL block. DBMS_OUTPUT is an Oracle supplied
package and PUT_LINE is a procedure within it. To use this you need to specify the
information    you     want      printed,    in   parentheses,     following    the
DBMS_OUTPUT.PUT_LINE command as shown in the above code:

              DBMS_OUTPUT.PUT_LINE (‘The quarterly income of the library
       is:          ’|| QuarterlyInc);

For DBMS_OUTPUT.PUT_LINE to work, you need to run the iSQL*Plus command
SET SERVEROUTPUT ON.

iSQL*Plus host variables (also known as bind variables) are used to pass runtime
values from the PL/SQL block back to the iSQL*Plus environment. These variables
can be referenced in a PL/SQL block by placing a colon(:) before the variable.


© SQL Star International Ltd                                                        18
Introduction to PL/SQL15



The keyword VARIABLE is used to declare a bind variable. The syntax is:

              VARIABLE <variable_name> datatype

The syntax to display the variable value is:

              PRINT <variable_name>

Bind variables cannot be referred within the PL/SQL block of a function, procedure or
a package.

In a PL/SQL block, to differentiate between host variables and declared PL/SQL
variables, prefix the former with a colon(:).

The code wherein you had calculated the quarterly income using substitution
variables can be re-written using host variables as follows:


              VARIABLE QuarterlyInc NUMBER
              DECLARE
                    AnnualIncome NUMBER(7):= &AnnInc;
              BEGIN
                    :QuarterlyInc:= AnnualIncome/4;
              END;
              /
              old   2: AnnualIncome NUMBER(7):= &AnnInc;
              new   2: AnnualIncome NUMBER(7):= 80000;

              PL/SQL procedure successfully completed.

              PRINT QuarterlyInc


              QUARTERLYINC
              ------------
                     20000


The above example shows the Host variable being assigned a value inside a PL/SQL
block. To assign a value to a host variable outside the Pl/SQL block following can be
done:-
       SQL > VARIABLE QuarterlyInc NUMBER
       SQL > Exec :QuarterlyInc := 20000
       SQL> PRINT QuarterlyInc

              QUARTERLYINC
              ------------
                     20000



© SQL Star International Ltd                                                            19
Introduction to PL/SQL15




Where,
Exec stand for Execute privilege.




Nested Blocks
PL/SQL allows blocks to be nested wherever you can have an executable statement.
[This makes the nested block a statement.] Hence, the executable part of a block
can be broken down into smaller blocks. Even the exception section can contain
nested blocks.

Variable Scope
Issues that concern references to identifiers can be resolved taking into account their
scope and visibility.
By scope, we mean that region of a program unit from which an identifier can be
referenced. For instance, a variable in the declarative section can be referenced from
the exception section of that block.


The diagram shown below illustrates the concept of nested blocks and variable
scope.



                                                                            By
                                                                            visibility,
                                                                            we mean




© SQL Star International Ltd                                                        20
Introduction to PL/SQL15


the regions from which an identifier can be referenced without using a qualified
name.

The following code snippet shows how to qualify identifiers:

        <<outer_blk>> --Block label
        DECLARE --This is the parent block
              JoiningDt DATE;
        BEGIN
              DECLARE --his is the child block
                    JoiningDt DATE;
              BEGIN
                    …
                  outer_blk.JoiningDt :=TO_DATE (’20- JAN-1998’, ‘DD-MON-
YY’);
               END;
        …
        END;
        /

In the code snippet, a variable with the same name as the variable declared in the
outer block is declared in the inner block. To reference the outer block variable in the
inner block, the variable is qualified by prefixing it with the block name.
Identifiers are considered local to the PL/SQL block in which they are declared, and
are considered global to all its sub-blocks. Within the sub-block, only local identifiers
are visible because to reference the global identifiers you must use a qualified name.
If a block cannot find the identifier declared locally, it will look up to declarative
section of the enclosing block (parent block). However, the block will never look
down to the enclosed blocks (child blocks).

Look at the following code and determine the variable scope:

        <<OUTER_BLK>>
        DECLARE
              vSal NUMBER(8,2) := 50000;
              vComm NUMBER(8,2) := vSal * 0.10;
              vNote VARCHAR2(200) := ‘Eligible for commission’;
        BEGIN
              DECLARE
                    vSal NUMBER(8,2) := 90000;
                    vComm NUMBER (4) := 0;
                    vAnnualComp NUMBER(8,2) := vSal + vComm;
              BEGIN
                    vNote := ‘Manager not’||vNote;
                          OUTER_BLK.vComm := vSal * 0.20;
        END;
                          vNote := ‘Salesman’||vNote;


        END;



© SQL Star International Ltd                                                          21
Introduction to PL/SQL15


       /


Based on the rules of scoping, determine values of:

    vNote at position 1
    vAnnualComp at position 2
    vComm at position 1
    OUTER_BLK.vComm at position 1
    vComm at position 2
    vNote at position 2

Guidelines for Writing PL/SQL Code
Programs can be indented using carriage return,tabs and aligning keywords in the
same line at different levels.Writing so, the task of debugging is made simpler.
While writing programs we can follow a case convention, though PL/SQL is not case
sensitive. For instance:-

      •    All keywords should be written in uppercase.
      •    They must be aligned in the same line.
      •    Table names and column names are to be in Initcap and lower case
           respectively.

Indented programs improve the performance in those cases where similar
statements are to be issued repeatedly because there is no need to parse the
statements again.

Let us write a program following all the rules stated above.

      DECLARE
            AnnualIncome NUMBER(7):= 60000;
            QuarterlyInc    NUMBER(8,2);
      BEGIN
            QuarterlyInc:= AnnualIncome/4;
            DBMS_OUTPUT.PUT_LINE(‘The    Quarterly                income     is    ‘||
QuarterlyInc);
      END;

       /

Here, the keywords are aligned in the same line but at different levels. This
improves readability of the code.




© SQL Star International Ltd                                                        22
Introduction to PL/SQL15



Summary

In this chapter, you have learnt that:

 PL/SQL bridges gap between SQL and a procedural language.

  Two types of PL/SQL blocks are:
       1. Anonymous or unnamed blocks which are not stored in database and
       compiled each time they are executed.

         2. Named Blocks which are compiled only once and stored in the database.

  The three sections of a PL/SQL Block are:
       1. Declarative Section, where all the variables used in the program are
       declared. This is optional. Keyword: DECLARE

         2. Executable Section where actual logic of the program lies. Keyword:
 BEGIN

        3. Exception Section where all the errors are handled. This section is
 optional.                    Keyword: EXCEPTION

         4. END to end the PL/SQL program.

  PL/SQL variables are declared and are accessible only within that PL/SQL block.
   Non- PL/SQL variables are declared outside the PL/SQL block and are available
   throughout the session.

  Two new datatypes FLOAT and DOUBLE introduced in this release help users in
   computing complex calculations.

  Nesting of blocks is allowed to have good control on the scope of the variables.
                 Nested Blocks can also have exception sections.




© SQL Star International Ltd                                                     23
Introduction to PL/SQL15




Lab Exercises
1.    Identify whether the following declarations are correct or incorrect:

          a) DECLARE
             empID NUMBER(5);

          b) DECLARE
              str1, str2, str3 VARCHAR2(20);

          c) DECLARE
              hiredate   DATE NOT NULL;

          d) DECLARE
             on BOOLEAN := 5;

2.    Create an anonymous block to display the phrase “Welcome to the world of
PL/SQL”.




3.     Create a block that declares two variables, one of VARCHAR2 type and the
other of NUMBER type. Assign the following values to the variables and display the
output on the screen.




© SQL Star International Ltd                                                     24
Introduction to PL/SQL15


4.    Write a PL/SQL code to display the ID, Last Name, job ID and salary of an
employee?




5.    Among the following which datatypes are enhancements of Oracle10g?

             a)    BINARY_INTEGER

             b)    BINARY_FLOAT

             c)    BINARY_DOUBLE



6.    Display the following text using quote operator q:

         I’m Oracle certified,you’re not.




© SQL Star International Ltd                                                    25

More Related Content

What's hot

Ebs 12.2 con9021_pdf_9021_0001
Ebs 12.2 con9021_pdf_9021_0001Ebs 12.2 con9021_pdf_9021_0001
Ebs 12.2 con9021_pdf_9021_0001jucaab
 
Ebs troubleshooting con9019_pdf_9019_0001
Ebs troubleshooting con9019_pdf_9019_0001Ebs troubleshooting con9019_pdf_9019_0001
Ebs troubleshooting con9019_pdf_9019_0001jucaab
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
Oracle_EBS
Oracle_EBSOracle_EBS
Oracle_EBSbmujahid
 
Ebs architecture con9036_pdf_9036_0001
Ebs architecture con9036_pdf_9036_0001Ebs architecture con9036_pdf_9036_0001
Ebs architecture con9036_pdf_9036_0001jucaab
 
Ebs idm con9020_pdf_9020_0001
Ebs idm con9020_pdf_9020_0001Ebs idm con9020_pdf_9020_0001
Ebs idm con9020_pdf_9020_0001jucaab
 
Introduction to embedded sql for NonStop SQL
Introduction to embedded sql for NonStop SQLIntroduction to embedded sql for NonStop SQL
Introduction to embedded sql for NonStop SQLFrans Jongma
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Trainingsuresh
 
JEE Course - JEE Overview
JEE Course - JEE  OverviewJEE Course - JEE  Overview
JEE Course - JEE Overviewodedns
 
java database connection (jdbc)
java database connection (jdbc)java database connection (jdbc)
java database connection (jdbc)Sanjay Gunjal
 
Oracle apps file system
Oracle apps file systemOracle apps file system
Oracle apps file systemVivek Verma
 
Oracle Applications R12 architecture
Oracle Applications R12 architectureOracle Applications R12 architecture
Oracle Applications R12 architectureSekhar Byna
 
J2EE Architecture Explained
J2EE  Architecture ExplainedJ2EE  Architecture Explained
J2EE Architecture ExplainedAdarsh Kr Sinha
 

What's hot (20)

Ebs 12.2 con9021_pdf_9021_0001
Ebs 12.2 con9021_pdf_9021_0001Ebs 12.2 con9021_pdf_9021_0001
Ebs 12.2 con9021_pdf_9021_0001
 
Ebs troubleshooting con9019_pdf_9019_0001
Ebs troubleshooting con9019_pdf_9019_0001Ebs troubleshooting con9019_pdf_9019_0001
Ebs troubleshooting con9019_pdf_9019_0001
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
 
Pl sql content
Pl sql contentPl sql content
Pl sql content
 
Oracle_EBS
Oracle_EBSOracle_EBS
Oracle_EBS
 
Ebs architecture con9036_pdf_9036_0001
Ebs architecture con9036_pdf_9036_0001Ebs architecture con9036_pdf_9036_0001
Ebs architecture con9036_pdf_9036_0001
 
Ebs idm con9020_pdf_9020_0001
Ebs idm con9020_pdf_9020_0001Ebs idm con9020_pdf_9020_0001
Ebs idm con9020_pdf_9020_0001
 
Introduction to embedded sql for NonStop SQL
Introduction to embedded sql for NonStop SQLIntroduction to embedded sql for NonStop SQL
Introduction to embedded sql for NonStop SQL
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Training
 
RESUME
RESUMERESUME
RESUME
 
Jddk
JddkJddk
Jddk
 
Oracle etl openworld
Oracle etl openworldOracle etl openworld
Oracle etl openworld
 
Jooq java object oriented querying
Jooq java object oriented queryingJooq java object oriented querying
Jooq java object oriented querying
 
JEE Course - JEE Overview
JEE Course - JEE  OverviewJEE Course - JEE  Overview
JEE Course - JEE Overview
 
java database connection (jdbc)
java database connection (jdbc)java database connection (jdbc)
java database connection (jdbc)
 
Oracle apps file system
Oracle apps file systemOracle apps file system
Oracle apps file system
 
MFC Whitepaper
MFC WhitepaperMFC Whitepaper
MFC Whitepaper
 
Oracle Applications R12 architecture
Oracle Applications R12 architectureOracle Applications R12 architecture
Oracle Applications R12 architecture
 
Ebook7
Ebook7Ebook7
Ebook7
 
J2EE Architecture Explained
J2EE  Architecture ExplainedJ2EE  Architecture Explained
J2EE Architecture Explained
 

Viewers also liked (10)

Vai tu zini, kāds līderis gribi būt
Vai tu zini, kāds līderis gribi būtVai tu zini, kāds līderis gribi būt
Vai tu zini, kāds līderis gribi būt
 
Zalantza dantza
Zalantza dantzaZalantza dantza
Zalantza dantza
 
Par to kas TU ESI
Par to kas TU ESIPar to kas TU ESI
Par to kas TU ESI
 
Grasslands animals
Grasslands animalsGrasslands animals
Grasslands animals
 
Fdi in retail sector
Fdi in retail sectorFdi in retail sector
Fdi in retail sector
 
Talent management
Talent managementTalent management
Talent management
 
Fdi in retail
Fdi in retailFdi in retail
Fdi in retail
 
Data 101
Data 101Data 101
Data 101
 
Hrm in uk
Hrm in ukHrm in uk
Hrm in uk
 
Treasury bills
Treasury billsTreasury bills
Treasury bills
 

Similar to Chapter 1

What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxshivanikaale214
 
PLSQL Notes.pptx
PLSQL Notes.pptxPLSQL Notes.pptx
PLSQL Notes.pptxSHRISANJAY4
 
Unit 4 rdbms study_material
Unit 4  rdbms study_materialUnit 4  rdbms study_material
Unit 4 rdbms study_materialgayaramesh
 
Plsql overview
Plsql overviewPlsql overview
Plsql overviewGagan Deep
 
Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPTSujayaBiju
 
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.ppt
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.pptOracle_PLSQL_basic_tutorial_with_workon_Exercises.ppt
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.pptDheerajKashnyal
 
Introduction to PL/SQL
Introduction to PL/SQLIntroduction to PL/SQL
Introduction to PL/SQLKailash N
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, proceduresVaibhav Kathuria
 
PL/SQL Interview Questions
PL/SQL Interview QuestionsPL/SQL Interview Questions
PL/SQL Interview QuestionsSrinimf-Slides
 
1. In a 200 words or less explain the differences between SQL and .docx
1. In a 200 words or less explain the differences between SQL and .docx1. In a 200 words or less explain the differences between SQL and .docx
1. In a 200 words or less explain the differences between SQL and .docxSONU61709
 
Database management system chapter5
Database management system chapter5Database management system chapter5
Database management system chapter5Pranab Dasgupta
 

Similar to Chapter 1 (20)

What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
 
Pl sql chapter 1
Pl sql chapter 1Pl sql chapter 1
Pl sql chapter 1
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
 
pl_sql.ppt
pl_sql.pptpl_sql.ppt
pl_sql.ppt
 
PLSQL Notes.pptx
PLSQL Notes.pptxPLSQL Notes.pptx
PLSQL Notes.pptx
 
Unit 4 rdbms study_material
Unit 4  rdbms study_materialUnit 4  rdbms study_material
Unit 4 rdbms study_material
 
Bn 1018 demo pl sql
Bn 1018 demo  pl sqlBn 1018 demo  pl sql
Bn 1018 demo pl sql
 
Plsql overview
Plsql overviewPlsql overview
Plsql overview
 
Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPT
 
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.ppt
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.pptOracle_PLSQL_basic_tutorial_with_workon_Exercises.ppt
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.ppt
 
PLSql.pptx
PLSql.pptxPLSql.pptx
PLSql.pptx
 
Introduction to PL/SQL
Introduction to PL/SQLIntroduction to PL/SQL
Introduction to PL/SQL
 
Les01
Les01Les01
Les01
 
Indexdfg
IndexdfgIndexdfg
Indexdfg
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
PL/SQL Interview Questions
PL/SQL Interview QuestionsPL/SQL Interview Questions
PL/SQL Interview Questions
 
Dbms 2011
Dbms 2011Dbms 2011
Dbms 2011
 
1. In a 200 words or less explain the differences between SQL and .docx
1. In a 200 words or less explain the differences between SQL and .docx1. In a 200 words or less explain the differences between SQL and .docx
1. In a 200 words or less explain the differences between SQL and .docx
 
D34010.pdf
D34010.pdfD34010.pdf
D34010.pdf
 
Database management system chapter5
Database management system chapter5Database management system chapter5
Database management system chapter5
 

Recently uploaded

USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 

Recently uploaded (20)

USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 

Chapter 1

  • 1. Introduction to PL/SQL15 Chapter 1 Introduction to PL/SQL Need for PL/SQL Benefits of Using PL/SQL PL/SQL Block Types and Constructs PL/SQL Block Structure Operators and SQL Functions in PL/SQL Variables Nested Blocks © SQL Star International Ltd 1
  • 2. Introduction to PL/SQL15 Objectives At the end of this chapter, you will be able to:  State the need for a procedural language in Oracle  Create PL/SQL blocks  Write nested blocks © SQL Star International Ltd 2
  • 3. Introduction to PL/SQL15 Introducing PL/SQL In the journey so far, you have learnt about the Structured Query Language (SQL). The Oracle software provides a language, Procedural Language/SQL (PL/SQL), which is an extension of SQL. PL/SQL implements modularity in the codes you write. It allows you to perform iterations and handle errors. Features like data hiding and error handling make PL/SQL a state-of-the-art language for databases. PL/SQL also allows data manipulation and SQL query statements to be included within procedural units of code. This makes PL/SQL a powerful transaction processing mechanism. Need for PL/SQL The requirement for PL/SQL was mainly due to the need to centralize automated business tasks. For example, if each employee in an organization maintains separate programs to manage their tasks and updates them at their discretion, it could create confusions, such as: • New employees or existing employees who are handed over someone else’s work, would have a problem understanding the process followed by the employee vis-à-vis the organization • Any change in business policy or functionality would have to be updated by all the employees individually in all relevant programs. In a centralized functionality this is avoided because all changes need to be made at one place. Changes will get reflected in the relevant codes and all users can access updated information. Benefits of Using PL/SQL The reasons for using PL/SQL are as follows:  Integrating with the Oracle server and Oracle development tools  Implementing performance enhancements in an application  Modularizing the development of programs  Implementing Portability  Declaration of variables  Programming with procedural language control structures  Handling errors © SQL Star International Ltd 3
  • 4. Introduction to PL/SQL15 Integration PL/SQL plays a key role in:  Oracle server, through stored procedures and functions, database triggers and packages  Oracle development tools, through Oracle Developer component triggers PL/SQL supports the use of SQL datatypes. With direct access provided by SQL, these shared datatypes integrate PL/SQL with the Oracle server data dictionary. Hence, PL/SQL successfully bridges the gap between access to database technology and the need for procedural language capabilities. Most applications such as Oracle Forms, Oracle Reports and Oracle Graphics, use shared libraries (that hold code), which can be accessed locally or remotely. To execute these stored codes, the Oracle tools have their own PL/SQL engine (independent of the engine present in the Oracle server). The engine first filters out the SQL statements to send them individually to the SQL statement executor in the Oracle server. It then processes the remaining procedural statements in the procedural statement executor in the PL/SQL engine. The procedural statement executor processes data, which is already inside the client environment and not in the database. This reduces the workload on the Oracle server and also the amount of memory required. Performance Enhancements of Applications When SQL statements are sent to the Oracle server one at a time, each statement results in a call to the Oracle server, leading to performance overhead and network traffic. If your application is SQL intensive, then instead of sending SQL statements individually to the server, you can put them into one block using PL/SQL and send the entire block to the server at one time. This reduces network traffic. PL/SQL also operates with Oracle development tools, thereby adding procedural processing power to these tools and enhancing performance. © SQL Star International Ltd 4
  • 5. Introduction to PL/SQL15 Modularized Program Development PL/SQL programs are made up of one or more blocks. These blocks may be individual ones or may be nested within another. That is, a block may represent a small part of another block, which may in turn be part of a whole unit of code. The units (procedures, functions or anonymous blocks) making up a PL/SQL program are called logical blocks. A diagrammatic representation of modularization is: The advantages associated with modularized development of programs are:  Logical groupings of related statements within blocks  Nesting blocks within larger blocks help build powerful programs  Breaking down complex problems into manageable sets of logical, well-defined modules, which can be implemented within blocks Portability PL/SQL is portable. That means, PL/SQL programs can be run wherever the Oracle server exists. There is no need to tailor them to suit each new environment. This is achieved because PL/SQL is native to the Oracle server, and therefore can be moved to any environment (operating system or platform) that supports the Oracle server. PL/SQL code can also be moved between the Oracle server and Oracle Developer applications by writing programs and creating libraries in different environments. © SQL Star International Ltd 5
  • 6. Introduction to PL/SQL15 Variable Declaration In PL/SQL, you can declare variables:  To use them in SQL and procedural statements  Belonging to different data types  Dynamically based on the structure of tables and columns in the database Programming with Procedural Language Control Structures PL/SQL allows the usage of control structures, which enable you to execute:  Sequence of statements conditionally  Sequence of statements iteratively in a loop  Individually the rows returned by multiple-row query Handling Errors PL/SQL implements error handling functionality by:  Processing Oracle server errors with error handling routines  Declaring your own error conditions and process them with error handlers PL/SQL Block Types and Constructs There are two block types and different types of constructs in PL/SQL. A block is a PL/SQL code. A construct is the way in which a block is written to implement different functionality. Block Types Logical blocks are the basic units of code that make up a PL/SQL program. The two kinds of PL/SQL blocks are:  Anonymous blocks  Named blocks or Subprograms Anonymous Blocks Anonymous blocks are declared at that point in an application from where they are to be executed and are passed to the PL/SQL engine for execution at runtime. These blocks are unnamed blocks. They can be embedded in the iSQL*Plus environment. An application trigger consists of these blocks. Subprograms Unlike anonymous blocks, named blocks or subprograms are given a name. These blocks can be invoked for execution and they can also accept parameters. © SQL Star International Ltd 6
  • 7. Introduction to PL/SQL15 Subprograms can be declared as Procedures or Functions. You declare a subprogram as a Procedure to perform an action, and you declare a subprogram as a Function to compute a value. Subprograms can be written and stored either at the server side or at the client side. Constructs There are various PL/SQL program constructs available that use the basic PL/SQL block. The availability of program constructs depends on the environment in which they are executed. The different program constructs are given below. © SQL Star International Ltd 7
  • 8. Introduction to PL/SQL15 PL/SQL Block Structure To write a PL/SQL block, you need to know the different parts of a PL/SQL block and what each part should hold. The structure of all PL/SQL blocks is the same. The only difference is that, if it is an anonymous block it is not given a name. A PL/SQL block has three sections . They are :  Declarative section  Executable section  Exception handling section The declarative section is where the variables and constants used in the body of the block are declared. Any cursors or user-defined error handlers that are used in the body are declared here. This section is optional. The executable section holds the set of statements or the logic of the tasks that are to be performed. You can include SQL statements to make changes to the database and PL/SQL statements to manipulate data in the block. The statements in this block are enclosed within the keywords BEGIN and END. This section is mandatory. The last section of a block is the exception section. Here a set of statements is written to handle any errors that might occur when the statements in the executable section are being executed. This section is optional . © SQL Star International Ltd 8
  • 9. Introduction to PL/SQL15 The diagramatic expression of PL/SQL block structure is given below. The syntax for writing a PL/SQL block is: DECLARE <variable name> datatype(size); BEGIN SQL statements; PL/SQL statements; EXCEPTION WHEN <exception name> THEN … END; / Some points that will help you write a block:  A line of PL/SQL text which contains group of characters known as lexical units. These units are classified as follows:  Delimiters are simple or compound symbols that have a special meaning to PL/SQL. The following table presents both the simple as well as the compound symbols: © SQL Star International Ltd 9
  • 10. Introduction to PL/SQL15  Identifiers are used to name PL/SQL program constructs such as Constants, Variables and Exceptions. The following points need to be kept in mind while using identifiers: • Identifiers can be up to 30 characters in length, but ensure they start with an alphabet. • Do not give the same name for the identifiers as the name of columns in a table used in the block. If so, then the Oracle server assumes that the table column is being referred. • An identifier consists of a letter, followed (optional) by other letters, numerals, underscores, dollar signs and number signs. The following characters are however illegal: Abc&efg – illegal ampersand Abc-efg – illegal hyphen Abc/efg – illegal slash Abc efg – illegal space • Identifiers should not be reserved words except when they are used within double quotes, for instance “INSERT”.  Literals are made up of definite values such as character, numeric, string or Boolean values, not represented by identifiers. These are case sensitive. © SQL Star International Ltd 10
  • 11. Introduction to PL/SQL15 Literals are of two types: • Character literals: are all the printable characters such as letters, numerals, spaces, and special symbols. Specify character literals in single quotes. • Numeric literals: are represented either by a simple value such as –12 or by a scientific notation such as 3E6. Comments are extra information given by the programmer to improve readability in a code, to enable documenting in each phase and debugging. PL/SQL code can be commented in two ways: • Single line comment represented by -- • Multi line comment represented by /* */  Use a semicolon (;) at the end of all SQL and PL/SQL control statements and the END keyword.  Do not use semicolons after the keywords DECLARE, BEGIN and EXCEPTION.  Increase the readability of the block by writing the keywords in uppercase.  Use a slash (/) to terminate a PL/SQL block on a line by itself. Using Quotes in Literals Oracle 10g allows you to define your own string delimiters to remove the need to double up any single quotes. SET SERVEROUTPUT ON BEGIN --original code DBMS_OUTPUT.PUT_LINE(‘He is New Jersey Library ‘’s Member!’); -- using quote symbol DBMS_OUTPUT.PUT_LINE(q’# He is New Jersey Library‘s Member!#’); DBMS_OUTPUT.PUT_LINE(q’[ He is New Jersey Library‘s © SQL Star International Ltd 11
  • 12. Introduction to PL/SQL15 Member !]’); END; / He is New Jersey Library‘s Member! He is New Jersey Library‘s Member! He is New Jersey Library‘s Member ! PL/SQL procedure successfully completed Operators in PL/SQL The following operators are supported in PL/SQL:  Arithmetic  Logical  Relational or Comparison  Concatenation  Exponentiation [Represented by (**)] SQL Functions in PL/SQL Statements All the SQL functions can also be used in procedural statements in a block. These include:  Single-row number and character functions  Datatype conversion functions  Date functions  Timestamp functions  GREATEST and LEAST functions The functions that cannot be used in procedural statements are:  DECODE  Group functions like AVG, MIN, MAX, COUNT, SUM, STDDEV and VARIANCE. These functions work only on a group of rows in a table and hence, they can be used only with the SQL statements in a PL/SQL block. Variables A variable are named memory locations used to store data temporarily. The data stored in variables is used in the blocks and then processed. When the processing is completed, the data held in the variables may be written to the database or simply erased in case of session wide variables. Why is a Variable used? A Variable stores data temporarily. It manipulates the stored data and performs calculations with the data without accessing the database. Once declared, variables © SQL Star International Ltd 12
  • 13. Introduction to PL/SQL15 can be used repeatedly in an application by referencing them in other statements in the block. When variables are declared using %TYPE and %ROWTYPE (more information is provided later in the chapter), you are infact basing the variable declaration on the column definition of a table. In this case, if the column definition changes, then the variable declarations also changes accordingly. This helps in data independence, reduces maintenance cost and allows the program to adjust to the new business logic. How to handle variables in PL/SQL? In a PL/SQL block, variables are:  Declared and initialized in the declarative section of the block.  Assigned new values in the executable section. On doing so, the existing value is replaced with the newly assigned value. Care must be taken to see that a variable being referred to is already declared in the declarative section. Forward references cannot be made. Types of Variables Variables are of two types. They are:  PL/SQL variables  Non-PL/SQL variables PL/SQL Variables PL/SQL variables have a data type that specifies a storage format, constraints and also valid range of values. The data types used to declare PL/SQL variables are:  Scalar data types are those that correspond to database column types. These data types hold only a single value. The base scalar data types include:  CHAR  VARCHAR2  LONG  LONG RAW  NUMBER  BINARY_INTEGER  PLS_INTEGER  BINARY_FLOAT  BINARY_DOUBLE  BOOLEAN  DATE  TIMESTAMP  TIMESTAMP WITH TIMEZONE  TIMESTAMP WITH LOCAL TIMEZONE  INTERVAL YEAR TO MONTH  INTERVAL DAY TO SECOND © SQL Star International Ltd 13
  • 14. Introduction to PL/SQL15 Binary_Float and Binary_Double are the two new Datatypes introduced in Oracle10g.They represent floating point numbers in IEEE 754 format (Institute of Electrical and Electronic Engineers) and require 5 byte and 9 bytes to store the values respectively. IEEE format s supported by most of the computer system operating through native processor instructions thereby helping us to carry out complex computations using floating point data.   Composite data types are those that are defined by users. They enable you to manipulate groups of data in PL/SQL blocks  Reference data types are those that hold values pointing to other objects. These are also known as pointers.  LOB (large object) data types: are those that hold values, which specify the location of large objects such as graphic images. These values are known as locators. Large objects are stored in the same database as the table but not within the table. LOB data type allows you to store unstructured data of a maximum of 8-128 terabytes. This data could be a movie clip or a graphic image or a sound wave form. LOBs are further classified into:  CLOB (Character Large Objects) is used to store large blocks of character data of a single byte.  BLOB (Binary Large Object) is used to store large binary objects within the database.  BFILE (Binary File) is used to store large binary objects that are in the operating system files outside the database.  NCLOB (National Language Character Large Objects), are used to store large blocks of NCHAR data that may be single-byte or fixed-width multiple bytes The syntax for declaring PL/SQL variables is: identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; Where, identifier is the name assigned to the variable declared. CONSTANT specifies a constraint that the value of the variable cannot change. Constant variables must be initialized. While declaring a variable as a constant, the CONSTANT keyword must precede the datatype specification. DATATYPE specifies the type of data the variable can hold. It could be scalar, composite, reference or LOB datatype. NOT NULL specifies a constraint that the variable must contain a value. Therefore, NOT NULL variables must be initialized. := is the assignment operator used to assign an expression to a variable. Instead of the assignment operator, the DEFAULT expr (expression) can be used to assign values to the variables. © SQL Star International Ltd 14
  • 15. Introduction to PL/SQL15 By default, all variables are initialized to NULL. To prevent null values, variables are initialized using the DEFAULT keyword. The following code snippet shows how PL/SQL variables are declared in the declarative section of a block: DECLARE FirstName CHAR(20); BranchID CHAR(7) NOT NULL: = ‘09RANNJ’; FeeAmt CONSTANT NUMBER(2): = 15; CatgName CHAR(15) DEFAULT ‘Fiction’; % TYPE Attribute If you need to store a database column value in a variable or write a value from a variable to a database column, then the data type of the variable needs to be the same as that of the database column. You can use the %TYPE attribute to declare a variable to be of the same data type as that of a previously declared variable or database column. Incorrect variable data types generate PL/SQL errors during execution. When you want to declare a variable using a table attribute instead of the datatype the syntax is <variable_name> table.columnname%TYPE For example, in case you want to declare a variable that will store the address of a library member, you will write in the following syntax: DECLARE Address VARCHAR2(45); But, the above declaration will result in an error when an attempt is made to populate the variable with address details of members from the database table. This is because there is a mismatch in type specification of the variable. The datatype width of the vAddress column in table Member is 50, but you have declared it as 45. To overcome this, declare the variable using %TYPE attribute as follows: DECLARE Address Member.vAddress%TYPE; This statement declares a variable whose datatype and width is based on the vAddress column. If you want to declare a variable of the same type as a previously declared variable then the syntax is <variable_name> variable_name%TYPE © SQL Star International Ltd 15
  • 16. Introduction to PL/SQL15 Using %TYPE attribute to declare a variable based on a previously declared variable, is illustrated in the section dealing with the iSQL*Plus variables within PL/SQL blocks. Datatype and Variable size is determined when the block is compiled. So even if there is a change in the database column datatype the code manages the changed datatype information. Data Conversion Functions In any programming language generally, we have to deal with different datatypes simultaneously or receive data which is not in the default format. In such cases, Oracle server implicitly converts data into valid datatypes wherever feasible. Explicit conversions come into the scenario where automatic conversions are not possible. Oracle Server takes care of implicit conversion between 1. Character and Number 2. Character and Date But how is it done? Let us take an example. DECLARE cons_nfine NUMBER(3):=50; cons_extra_fine VARCHAR2(20):=’5'; tot_fine Transaction.nfine%TYPE; BEGIN tot_fine:= cons_nfine+cons_extra_fine; DBMS_OUTPUT.PUT_LINE(‘The total fine payable is Rs.‘|| tot_fine); END; / So, did you notice something? Variable cons_nfine is of number datatype and cons_extra_fine is of VARCHAR2 datatype. While assigning the result to tot_fine variable, cons_extra_fine is converted to number by PL/SQL executer and then the operation is performed. © SQL Star International Ltd 16
  • 17. Introduction to PL/SQL15 To perform explicit conversion, following built in functions can be used. to_char() to_number() to_date() to_Binary_float() to_Binary_double() DECLARE v_Date date:= to_Date( ‘April 04 2007’,’Month dd YYYY’); BEGIN DBMS_OUTPUT.PUT_LINE(‘You have entered ‘ ||v_Date ||’ as input’); END; / Example to show the usage of new datatypes. DECLARE l_binary_float BINARY_FLOAT; l_binary_double BINARY_DOUBLE; BEGIN l_binary_float := 2.1f; l_binary_double := 2.00001d; DBMS_OUTPUT.PUT_LINE(l_binary_double); DBMS_OUTPUT.PUT_LINE(l_binary_float); l_binary_float := TO_BINARY_FLOAT(2.1); l_binary_double := TO_BINARY_DOUBLE(2.00001); DBMS_OUTPUT.PUT_LINE(l_binary_double); DBMS_OUTPUT.PUT_LINE(l_binary_float); END; / © SQL Star International Ltd 17
  • 18. Introduction to PL/SQL15 Non-PL/SQL Variables Since PL/SQL has neither input nor output capabilities, it relies on the environment in which it is executed in order to pass values into and out of a PL/SQL block. The following non-PL/SQL variables can be used within PL/SQL blocks:  Substitution variables  Host variables Substitution variables are those that you can use to pass values to a PL/SQL block at runtime. To reference a substitution variable in a block, prefix it with an ampersand (&). Before the block is executed the values for the variables are substituted with the values passed. Hence, you cannot input different values for the substitution variables using a loop. The substitution variable can be replaced only by one value. Here is an example showing the use of substitution variables within PL/SQL blocks. Suppose, the library wants to calculate its quarterly income based on its annual income. To do this, it declares a substitution variable, which would prompt the user to enter the figure of annual income. Based on the value entered, the quarterly income would be calculated. DECLARE AnnualIncome NUMBER (7): = &annualinc; QuarterlyInc AnnualIncome%TYPE; -—declaring variable based on previously declared variable using --%TYPE attribute. BEGIN QuarterlyInc:= AnnualIncome/4; DBMS_OUTPUT.PUT_LINE (‘The quarterly income of the library is: ’|| QuarterlyInc); END; / In the above block, to display the quarterly income calculated, you can specify the DBMS_OUTPUT.PUT_LINE in the PL/SQL block. DBMS_OUTPUT is an Oracle supplied package and PUT_LINE is a procedure within it. To use this you need to specify the information you want printed, in parentheses, following the DBMS_OUTPUT.PUT_LINE command as shown in the above code: DBMS_OUTPUT.PUT_LINE (‘The quarterly income of the library is: ’|| QuarterlyInc); For DBMS_OUTPUT.PUT_LINE to work, you need to run the iSQL*Plus command SET SERVEROUTPUT ON. iSQL*Plus host variables (also known as bind variables) are used to pass runtime values from the PL/SQL block back to the iSQL*Plus environment. These variables can be referenced in a PL/SQL block by placing a colon(:) before the variable. © SQL Star International Ltd 18
  • 19. Introduction to PL/SQL15 The keyword VARIABLE is used to declare a bind variable. The syntax is: VARIABLE <variable_name> datatype The syntax to display the variable value is: PRINT <variable_name> Bind variables cannot be referred within the PL/SQL block of a function, procedure or a package. In a PL/SQL block, to differentiate between host variables and declared PL/SQL variables, prefix the former with a colon(:). The code wherein you had calculated the quarterly income using substitution variables can be re-written using host variables as follows: VARIABLE QuarterlyInc NUMBER DECLARE AnnualIncome NUMBER(7):= &AnnInc; BEGIN :QuarterlyInc:= AnnualIncome/4; END; / old 2: AnnualIncome NUMBER(7):= &AnnInc; new 2: AnnualIncome NUMBER(7):= 80000; PL/SQL procedure successfully completed. PRINT QuarterlyInc QUARTERLYINC ------------ 20000 The above example shows the Host variable being assigned a value inside a PL/SQL block. To assign a value to a host variable outside the Pl/SQL block following can be done:- SQL > VARIABLE QuarterlyInc NUMBER SQL > Exec :QuarterlyInc := 20000 SQL> PRINT QuarterlyInc QUARTERLYINC ------------ 20000 © SQL Star International Ltd 19
  • 20. Introduction to PL/SQL15 Where, Exec stand for Execute privilege. Nested Blocks PL/SQL allows blocks to be nested wherever you can have an executable statement. [This makes the nested block a statement.] Hence, the executable part of a block can be broken down into smaller blocks. Even the exception section can contain nested blocks. Variable Scope Issues that concern references to identifiers can be resolved taking into account their scope and visibility. By scope, we mean that region of a program unit from which an identifier can be referenced. For instance, a variable in the declarative section can be referenced from the exception section of that block. The diagram shown below illustrates the concept of nested blocks and variable scope. By visibility, we mean © SQL Star International Ltd 20
  • 21. Introduction to PL/SQL15 the regions from which an identifier can be referenced without using a qualified name. The following code snippet shows how to qualify identifiers: <<outer_blk>> --Block label DECLARE --This is the parent block JoiningDt DATE; BEGIN DECLARE --his is the child block JoiningDt DATE; BEGIN … outer_blk.JoiningDt :=TO_DATE (’20- JAN-1998’, ‘DD-MON- YY’); END; … END; / In the code snippet, a variable with the same name as the variable declared in the outer block is declared in the inner block. To reference the outer block variable in the inner block, the variable is qualified by prefixing it with the block name. Identifiers are considered local to the PL/SQL block in which they are declared, and are considered global to all its sub-blocks. Within the sub-block, only local identifiers are visible because to reference the global identifiers you must use a qualified name. If a block cannot find the identifier declared locally, it will look up to declarative section of the enclosing block (parent block). However, the block will never look down to the enclosed blocks (child blocks). Look at the following code and determine the variable scope: <<OUTER_BLK>> DECLARE vSal NUMBER(8,2) := 50000; vComm NUMBER(8,2) := vSal * 0.10; vNote VARCHAR2(200) := ‘Eligible for commission’; BEGIN DECLARE vSal NUMBER(8,2) := 90000; vComm NUMBER (4) := 0; vAnnualComp NUMBER(8,2) := vSal + vComm; BEGIN vNote := ‘Manager not’||vNote; OUTER_BLK.vComm := vSal * 0.20; END; vNote := ‘Salesman’||vNote; END; © SQL Star International Ltd 21
  • 22. Introduction to PL/SQL15 / Based on the rules of scoping, determine values of:  vNote at position 1  vAnnualComp at position 2  vComm at position 1  OUTER_BLK.vComm at position 1  vComm at position 2  vNote at position 2 Guidelines for Writing PL/SQL Code Programs can be indented using carriage return,tabs and aligning keywords in the same line at different levels.Writing so, the task of debugging is made simpler. While writing programs we can follow a case convention, though PL/SQL is not case sensitive. For instance:- • All keywords should be written in uppercase. • They must be aligned in the same line. • Table names and column names are to be in Initcap and lower case respectively. Indented programs improve the performance in those cases where similar statements are to be issued repeatedly because there is no need to parse the statements again. Let us write a program following all the rules stated above. DECLARE AnnualIncome NUMBER(7):= 60000; QuarterlyInc NUMBER(8,2); BEGIN QuarterlyInc:= AnnualIncome/4; DBMS_OUTPUT.PUT_LINE(‘The Quarterly income is ‘|| QuarterlyInc); END; / Here, the keywords are aligned in the same line but at different levels. This improves readability of the code. © SQL Star International Ltd 22
  • 23. Introduction to PL/SQL15 Summary In this chapter, you have learnt that: PL/SQL bridges gap between SQL and a procedural language.  Two types of PL/SQL blocks are: 1. Anonymous or unnamed blocks which are not stored in database and compiled each time they are executed. 2. Named Blocks which are compiled only once and stored in the database.  The three sections of a PL/SQL Block are: 1. Declarative Section, where all the variables used in the program are declared. This is optional. Keyword: DECLARE 2. Executable Section where actual logic of the program lies. Keyword: BEGIN 3. Exception Section where all the errors are handled. This section is optional. Keyword: EXCEPTION 4. END to end the PL/SQL program.  PL/SQL variables are declared and are accessible only within that PL/SQL block. Non- PL/SQL variables are declared outside the PL/SQL block and are available throughout the session.  Two new datatypes FLOAT and DOUBLE introduced in this release help users in computing complex calculations.  Nesting of blocks is allowed to have good control on the scope of the variables. Nested Blocks can also have exception sections. © SQL Star International Ltd 23
  • 24. Introduction to PL/SQL15 Lab Exercises 1. Identify whether the following declarations are correct or incorrect: a) DECLARE empID NUMBER(5); b) DECLARE str1, str2, str3 VARCHAR2(20); c) DECLARE hiredate DATE NOT NULL; d) DECLARE on BOOLEAN := 5; 2. Create an anonymous block to display the phrase “Welcome to the world of PL/SQL”. 3. Create a block that declares two variables, one of VARCHAR2 type and the other of NUMBER type. Assign the following values to the variables and display the output on the screen. © SQL Star International Ltd 24
  • 25. Introduction to PL/SQL15 4. Write a PL/SQL code to display the ID, Last Name, job ID and salary of an employee? 5. Among the following which datatypes are enhancements of Oracle10g? a) BINARY_INTEGER b) BINARY_FLOAT c) BINARY_DOUBLE 6. Display the following text using quote operator q: I’m Oracle certified,you’re not. © SQL Star International Ltd 25