Anda di halaman 1dari 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 exception of the DUAL table).
Lowercase characters are also used for column names and user-defined procedure,
function, and variable names shown in code.
Uppercase characters are used for Oracle keywords and functions, for view, table,
schema, and column names shown in text, for column aliases that are not shown in
quotes, for packages, and for data dictionary views.
The spacing convention requires one space after a comma and one space before and
after operators that are not Oracle-specific, such as +, -, /, and <. There should be no
space between an Oracle-specific keyword or operator and an opening bracket, a closing
bracket and a comma, between the last part of a statement and the closing semicolon, or
before a statement.
String literals in single quotes are an exception to all convention rules provided. Please
use this convention for all interactive parts of this course.
-----------------------------------------------------------------------------------------------------------There are many tools that provide an environment for developing PL/SQL code. Oracle
provides several tools that can be used to write PL/SQL code.
Some of the development tools include:

Oracle SQL Developer

Oracle SQL*Plus

Oracle JDeveloper
Oracle SQL Developer

Oracle SQL Developer is a graphical tool that can be used to write PL/SQL code.
Oracle SQL*Plus
Oracle SQL*Plus is a window or command-line application that can be used to write
PL/SQL code.
Oracle JDeveloper
Oracle JDeveloper is a window-based integrated development environment (IDE) that can
be used to write PL/SQL code.
Oracle SQL Developer is a free graphical tool designed to improve your productivity and
simplify the development of everyday database tasks. With just a few clicks, you can
easily create and debug stored procedures, test SQL statements, and view optimizer
plans.
SQL Developer, the visual tool for database development, simplifies these tasks:

browsing and managing database objects

executing SQL statements and scripts

editing and debugging PL/SQL statements

creating reports
You can connect to any target Oracle database schema by using standard Oracle
database authentication. When connected, you can perform operations on objects in the
database.
Oracle SQL*Plus is a command-line application that enables you to submit SQL
statements and PL/SQL blocks for execution, and receive the results in an application or
command window.
SQL*Plus is

shipped with the database

installed on a client and on the database server system

accessed from an icon or the command line


Oracle JDeveloper allows developers to create, edit, test, and debug PL/SQL code by
using a sophisticated graphical user interface (GUI). Oracle JDeveloper is a part of
Oracle Developer Suite and is also available as a separate product.
When coding PL/SQL in Jdeveloper, you should consider these points:

You create a database connection to enable JDeveloper to access a database schema owner for
the subprograms.

You can then use the JDeveloper shortcut menus on the database connection to create a new
subprogram construct using the built-in JDeveloper Code Editor. This Editor provides an excellent
environment for PL/SQL development, with features such as different colors for syntactical
components of the PL/SQL language and code insight to rapidly locate procedures and functions in
supplied packages.
This is the final point to be considered when coding PL/SQL in JDeveloper:

You invoke a subprogram by using a Run command on the shortcut menu for the named
subprogram. The output appears in the JDeveloper Log Message window.

Note
JDeveloper provides color-coding syntax in the JDeveloper Code Editor and is
sensitive to PL/SQL language constructs and statements.

Question
Which statements best describe functionality capabilities in SQL Developer?
Options:
1.

SQL Developer can be used for browsing and managing database objects

2.

SQL Developer can be used for editing and debugging PL/SQL statements

3.

SQL Developer cannot be used for creating Oracle SQL reports

4.

You can invoke subprograms using the Run command

Answer
SQL Developer can be used for browsing and managing database objects and for
editing and debugging PL/SQL statements.
Option 1 is correct. SQL Developer can be used to manage and browse database
objects. You can navigate to, find, and select objects and you can display
information about the selected objects.
Option 2 is correct. SQL Developer can be used to edit and debug PL/SQL
statements, using SQL Worksheet.
Option 3 is incorrect. Using SQL Developer, you can create custom reports as well
as reports that are part of the base functionality.
Option 4 is incorrect. You can use the Run command from the shortcut menu in
JDeveloper to invoke a subprogram.

2. Using SQL Developer


To create a database connection using SQL Developer, you perform these steps:
Step 1: Double-click <your_path>\sqldeveloper\sqldeveloper.exe.
Step 2: On the Connections tabbed page, right-click Connections and select New
Connection.
Step 3: In the New / Select Database Connection dialog box, specify the Connection
Name, Username, and Password.
The next steps to create a database connection are
Step 4: Specify the Hostname and SID for the database you want to connect to.
Step 5: Click Test to ensure that the connection has been set correctly.
Step 6: Click Connect.
In the New / Select Database Connection dialog box, on the Oracle tabbed page, you
specify these options:

Hostname, which is the host system for the Oracle database

Port, which is the listener port

SID, which is the database name

Service name, which is the network service name for a remote database connection
If you select the Save Password check box, the password is saved to an XML file. As a
result, you are not prompted for the password after you close the SQL Developer
connection and open it again.
You can create any schema object in SQL Developer by using one of these methods:

executing a SQL statement in SQL Worksheet

using the shortcut menu


You can edit schema objects by using the Edit dialog box or one of the many contextsensitive menus.
You can also view the data definition language (DDL) for adjustments such as creating a
new object or editing an existing schema object.

When you connect to a database, a SQL Worksheet window for that connection is
automatically opened. You can use the SQL Worksheet to enter and execute SQL,
PL/SQL, and SQL*Plus statements.
The SQL Worksheet supports SQL*Plus statements to a certain extent. SQL*Plus
statements that are not supported by the SQL Worksheet are ignored and are not passed
to the database.
Within a worksheet, 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


You can display a SQL Worksheet by using either of these options:

select Tools > SQL Worksheet

click the Open SQL Worksheet icon


In the SQL Worksheet, you can use the Enter SQL Statement box to enter single or
multiple SQL statements. For a single statement, the semicolon at the end is optional.
When you enter the statement, the SQL keywords are automatically highlighted. To
execute a SQL statement, ensure that your cursor is within the statement and then click
Execute Statement. Alternatively, you can press the [F9] key.
To execute multiple SQL statements and see the results, click Run Script or press F5.
Here is a sample SQL statement in which the first statement is terminated with a
semicolon because there are multiple SQL statements. The cursor is in the first
statement. Therefore, when the statement is executed, results corresponding to the first
statement are displayed in the Results box.

Question
Which statement is true about using the SQL Worksheet?
Options:
1.

In the SQL Worksheet, you can execute SQL and PL/SQL statements

2.

SQL*Plus statements cannot be interpreted by SQL Worksheet

3.

Statements not supported by the SQL Worksheet are passed on to the database

4.

The SQL Worksheet window is not automatically opened when connecting to a


database

Answer
In the SQL Worksheet, you can execute SQL and PL/SQL statements.
Option 1 is correct. SQL Worksheet supports SQL statements, PL/SQL
statements, and some SQL*Plus commands.
Option 2 is incorrect. You can use the SQL Worksheet to enter and execute SQL,
PL/SQL, and SQL*Plus statements.
Option 3 is incorrect. SQL*Plus statements that are not supported by the SQL
Worksheet are ignored and are not sent to the database.
Option 4 is incorrect. When you connect to a database, a SQL Worksheet window
for that connection is automatically opened.

Question
Which statement best describes the functionality of SQL*Plus when using SQL
Developer?
Options:
1.

All SQL*Plus statements are supported by the SQL Worksheet

2.

It is not necessary to define the location of the SQL*Plus executable file to use any
of the SQL*Plus features within SQL Developer

3.

SQL*Plus statements must be interpreted by the SQL Worksheet before being


passed to the database

Answer
SQL*Plus statements must be interpreted by the SQL Worksheet before being
passed to the database.
Option 1 is incorrect. Not every SQL*Plus statement is supported by the SQL
Worksheet. For example, commands such as APPEND, ARCHIVE, ATTRIBUTE,
and BREAK are not supported.
Option 2 is incorrect. To use some specific features from within SQL Developer,
the path to the SQL*Plus executable must be defined within the tool.
Option 3 is correct. All SQL statements are interpreted by the SQL Worksheet
before being passed on to the database.

Summary
Oracle provides several tools that can be used to write PL/SQL code. These tools include
Oracle SQL Developer, Oracle SQL*Plus, and Oracle JDeveloper. Oracle SQL Developer
is a free graphical tool that helps improve your productivity and simplify the development
of everyday database tasks. Oracle SQL*Plus is a command-line application that enables
you to submit SQL statements and PL/SQL blocks for execution and receive results in an
application or command window. Oracle JDeveloper allows you to create, edit, test, and
debug PL/SQL code by using a sophisticated GUI.
You can create database connections and schema objects using SQL Developer. You can
use the SQL Worksheet to enter and execute SQL, PL/SQL, and SQL*Plus statements.
To execute a SQL statement, you click Execute Statement or press the F9 key.

Table of Contents
| Top of page |
| Learning objective |
| 1. Introducing PL/SQL development tools |
| 2. Using SQL Developer |
| Summary |
Copyright 2008 SkillSoft. All rights reserved.
SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks 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 blocks.

1. Overview of PL/SQL
Structured Query Language (SQL) is the primary language used to access and modify
data in a relational database. Because there are only a few SQL commands, you can
easily learn and use them.

Consider this sample SQL statement, which is simple and straightforward. However, if
you want to alter any data that is retrieved in a conditional manner, you will encounter the
limitations of SQL.
SELECT first_name, department_id, salary FROM employees;
Say you want to retrieve data for every employee, their department ID, and salary. You
also want to give varying bonuses to these employees, depending on their department's
performance and the employee's salary.
To do this, you need to execute the SELECT SQL statement, collect the data, and apply
logic to the data. One solution is to write a SQL statement for each department to give
bonuses to the employees in that department. Note that you also have to check the salary
component before deciding the bonus amount. This makes it a little complicated. You now
feel that it would be much easier if you had conditional statements. PL/SQL (Procedural
Language extension to Structured Query Language) is designed to meet such
requirements. It provides a programming extension to the already-existing SQL.
PL/SQL defines a block structure for writing executable units of code. Maintaining and
debugging the code is easier with such a well-defined structure. You can easily
understand the flow and execution of the program unit.
PL/SQL offers modern software engineering features such as data encapsulation,
exception handling, information hiding, and object orientation. It brings state-of-the-art
programming to the Oracle server and toolset.
PL/SQL provides these procedural constructs that are available in any third-generation
language (3GL):

variables, constants, and data types

control structures such as conditional statements and loops

reusable program units that are written once and executed many times
In a PL/SQL execution environment of an Oracle database server, a PL/SQL block
contains procedural statements and SQL statements. When you submit the PL/SQL block
to the server, the PL/SQL engine first parses the block. The PL/SQL engine identifies the
procedural statements and the SQL statements. It passes the procedural statements to
the procedural statement executor and the SQL statements to the SQL statement
executor individually.
The Oracle application development tools can also contain a PL/SQL engine. The tool
passes the blocks to its local PL/SQL engine. Therefore, all procedural statements are
executed locally and only the SQL statements are executed in the database. The engine
used depends on where the PL/SQL block is being invoked from.

These are the benefits of using PL/SQL:

integration of procedural constructs with SQL

improved performance

implementation of modularized program development

integration with tools

portability

exception handling
The most important advantage of PL/SQL is the integration of procedural constructs with
SQL. SQL is a nonprocedural language. When you issue a SQL command, the command
tells the database server what to do. However, you cannot specify how to do it. PL/SQL
integrates control statements and conditional statements with SQL, giving you better
control of your SQL statements and their execution.
Without PL/SQL, you would not be able to logically combine SQL statements as one unit.
If you have designed an application containing forms, you may have many different forms
with fields in each form.
When a form submits the data, you may have to execute a number of SQL statements,
which are sent to the database one at a time. This results in many network trips and one
call to the database for each SQL statement, thereby increasing network traffic and
reducing performance, especially in a client/server model.
With PL/SQL, you can combine all these SQL statements into a single program unit. The
application can then send the entire block of statements to the database, instead of
sending the SQL statements one at a time. This significantly reduces the number of
database calls. If the application is SQL intensive, you can use PL/SQL blocks to group
SQL statements before sending them to the Oracle database server for execution, thus
improving performance.
A basic unit in all PL/SQL programs is the block. Blocks can be in a sequence or they can
be nested in other blocks. By implementing modularized program development, you can

group logically related statements within blocks

nest blocks inside larger blocks to build powerful programs

break your application into smaller, manageable, and logically related modules, if you are
designing a complex application
maintain and debug the code
In PL/SQL, modularization is implemented using procedures, functions, and packages.

The PL/SQL engine is integrated in Oracle tools such as Oracle Forms and Oracle
Reports. When you use these tools, the locally available PL/SQL engine processes the
procedural statements; only the SQL statements are passed to the database.
PL/SQL programs are portable and can run anywhere an Oracle server runs, irrespective
of the operating system and the platform. You do not need to customize them to each
new environment. You can write portable program packages and create libraries that can
be reused in different environments.
PL/SQL enables you to handle exceptions efficiently. You can define separate blocks for
dealing with exceptions. PL/SQL shares the same data type system as SQL, with some
extensions, and uses the same expression syntax.

2. PL/SQL block structure


A basic PL/SQL block structure can include these keywords:

DECLARE

BEGIN

EXCEPTION

END
These three sections can be identified in a PL/SQL block:

declarative

executable

exception handling
declarative
The declarative section begins with the keyword DECLARE and ends when the executable
section starts. This section contains declarations of all variables, constants, cursors, and
user-defined exceptions that are referenced in the executable and exception sections. The
inclusion of the declarative section is optional.
executable
The executable section begins with the keyword BEGIN and ends with END. This section
essentially needs to have at least one statement and includes any number of PL/SQL
blocks to manipulate data in a block. This section contains SQL statements to retrieve data
from the database. The inclusion of the executable section is mandatory.
exception handling
The exception section is nested within the executable section. This section begins with the
keyword EXCEPTION and specifies the actions to perform when errors and abnormal

conditions arise in the executable section. The inclusion of the exception handling section
is optional.
In a PL/SQL block, the keywords DECLARE, BEGIN, and EXCEPTION are not terminated
by a semicolon. However, the keyword END, all SQL statements, and PL/SQL statements
must be terminated with a semicolon.
A PL/SQL program comprises one or more blocks. These blocks can be entirely separate
or nested within another block. These are the three types of blocks that make up a
PL/SQL program:

anonymous blocks
<code>[DECLARE] BEGIN --statements [EXCEPTION] END;</code>

procedures
<code>PROCEDURE name IS BEGIN --statements [EXCEPTION] END;</code>

functions
<code>FUNCTION name RETURN datatype IS BEGIN --statements RETURN
value; [EXCEPTION]END;</code>
Anonymous blocks are unnamed blocks. They are declared inline at the point in an
application where they are to be executed and are compiled each time the application is
executed. These blocks are not stored in the database. They are passed to the PL/SQL
engine for execution at run time. Triggers in Oracle Developer components consist of
such blocks. These anonymous blocks get executed at run time because they are inline.
If you want to execute the same block again, you have to rewrite the block. You are
unable to invoke or call the block that you wrote earlier because blocks are anonymous
and do not exist after they are executed.
Subprograms are complementary to anonymous blocks. They are named PL/SQL blocks
that are stored in the database. Because they are named and stored, you can invoke
them whenever you want, depending on your application. You can declare them either as
procedures or as functions. You typically use a procedure to perform an action and a
function to compute and return a value.

Note
A function is similar to a procedure, except that a function must return a value.
You can store subprograms at the server or application level. Using Oracle Developer
components, such as forms or reports, you can declare procedures and functions as part

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 PL/SQL program constructs that use the basic PL/SQL blocks and are
based on the environment in which they are executed:

anonymous blocks

application procedures or functions

stored procedures or functions

application or stored packages

database triggers

application triggers

object types
anonymous blocks
Anonymous blocks are embedded within an application or are issued interactively and are
available to all PL/SQL environments.
application procedures or functions
Application procedures or functions are named PL/SQL blocks stored in an Oracle Forms
Developer application or shared library. It can accept parameters and can be invoked
repeatedly by name. This program construct is available for Oracle Developer tools
components, for example, Oracle Forms Developer and Oracle Reports.
stored procedures or functions
Stored procedures or functions are named PL/SQL blocks stored in the Oracle server and
accept parameters. These can be invoked repeatedly by name and are available to Oracle
server or Oracle Developer tools.
application or stored packages
Application or stored packages are named PL/SQL modules that group related procedures,
functions, and identifiers. They are available to Oracle server and Oracle Developer tools
components, such as Oracle Forms Developer.
database triggers
Database triggers are PL/SQL blocks 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 DML.
application triggers
Application triggers are PL/SQL blocks that are associated either with a database table or
system events. They are fired automatically when triggered by a DML or a system event
respectively. They are available to Oracle Developer tools components, such as Oracle
Forms Developer.
object types

Object types are user-defined composite data types that encapsulate a data structure
along with the functions and procedures needed to manipulate the data. These blocks are
available to Oracle server and Oracle Developer tools.
To create an anonymous block by using SQL Developer, you need to execute these
steps:
Step 1: Enter the anonymous block in the SQL Developer workspace. The anonymous
block gets the first_name of the employee whose employee_id is 100, and stores it
in a variable called v_fname. Click Run Script to execute the anonymous block.
Step 2: After the block is executed, the message "anonymous block completed" is
displayed in the Script Output window.
PL/SQL does not have built-in input or output functionality. Therefore, you need to use
predefined Oracle packages for input and output. The output of the PL/SQL block after
the inclusion of the code for generating output is displayed. To get the output that is to be
displayed, you perform these steps:
Step 1: Click the DBMS Output tab. Then you click Enable DBMS Output. This
executes the SET SERVEROUTPUT ON command, which is displayed in the window. To
enable output in SQL*Plus, you must explicitly issue the SET SERVEROUTPUT ON
command.
Step 2: In this example, a value is stored in the v_fname variable. However, the value
has not been printed. Use the PUT_LINE procedure of the DBMS_OUTPUT package to
display the output. Pass the value that has to be printed as an argument to this
procedure. The procedure then outputs the argument. Click Run Script to execute the
anonymous block.

Question
Which statements best describe the PL/SQL block structure?
Options:
1.

The declarative section is optional

2.

The END statement represents the end of program execution

3.

The exception section is mandatory

4.

The executable section begins with a DECLARE statement

Answer
The declarative section is optional in PL/SQL blocks and the END statement
represents the end of program execution.

Option 1 is correct. The declaration section contains declarations of all variables,


constants, cursors, and user-defined exceptions that are referenced in the
executable and exception sections.
Option 2 is correct. The END statement represents the end of the PL/SQL
executable section.
Option 3 is incorrect. Exception blocks contain the actions to perform when errors
and abnormal conditions arise in the executable section, but these actions are not
required.
Option 4 is incorrect. The BEGIN statement, not the DECLARE statement,
represents the beginning of the executable section. It can contain SQL statements
to retrieve data from the database and PL/SQL statements to manipulate data in
the block.

Question
Which statement accurately describes a PL/SQL block type?
Options:
1.

Anonymous blocks are unnamed blocks that only run at the time of execution

2.

Stored procedures and functions provide the same functionality

3.

Subprograms are stored at the application level only

4.

Triggers are an example of anonymous code blocks

Answer
Anonymous blocks are unnamed blocks that only run at the time of execution.
Option 1 is correct. Anonymous blocks are unnamed blocks of code that are
compiled and executed at execution time. They are not stored in the database.
Option 2 is incorrect. Procedures are used to perform an operation, as are
functions. However, functions must return a value.
Option 3 is incorrect. Subprograms such as procedures and functions can be
stored at the server level as well as the application level.
Option 4 is incorrect. Triggers are an example of stored database code that is
triggered by specific events. They are named and can be re-used.

Question
Which statements are true for testing the output of a PL/SQL block?

Options:
1.

Output functionality must be enabled in SQL Developer

2.

PL/SQL has built-in output functionality

3.

When using SQL*Plus, output is automatically enabled

4.

You use the PUT_LINE procedure of the DBMS_OUTPUT package to display the
output

Answer
You must enable output in SQL Developer and use the PUT_LINE procedure of
the DBMS_OUTPUT package to display the output.
Option 1 is correct. You enable output in SQL Developer via the Enable Output
option. This will, in turn, execute the SET SERVEROUTPUT ON command.
Option 2 is incorrect. PL/SQL does not have built-in input or output functionality.
Therefore, you need to use predefined Oracle packages for input and output.
Option 3 is incorrect. To enable output in SQL*Plus, you must explicitly issue the
SET SERVEROUTPUT ON command.
Option 4 is correct. You use the PUT_LINE procedure of the DBMS_OUTPUT
package to display the output. It passes the value that has to be printed as an
argument to the procedure. The procedure then outputs the argument.

Summary
SQL is the primary structured query language that is used to access and modify data in a
relational database. PL/SQL is a programming extension to the already-existing SQL.
PL/SQL defines a block structure for writing executable units of code.
The PL/SQL block structure can include DECLARE, BEGIN, EXCEPTION, and END
keywords. In a PL/SQL block, the keywords DECLARE, BEGIN, and EXCEPTION are not
terminated by a semicolon. However, the keyword END, all SQL statements, and PL/SQL
statements must be terminated with a semicolon. Anonymous blocks, procedures, and
functions are the three types of blocks that make up a PL/SQL program.

Table of Contents
| Top of page |
| Learning objective |
| 1. Overview of PL/SQL |

| 2. PL/SQL block structure |


| Summary |
Copyright 2008 SkillSoft. All rights reserved.
SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

| Print | Contents | Close |

Introducing PL/SQL Variables


Learning objective

After completing this topic, you should be able to identify the steps for declaring and
initializing PL/SQL variables.

1. Introducing variables
With PL/SQL, you can declare variables and then use them in SQL and procedural
statements. Variables are mainly used for storage of data and manipulation of stored
values.
This sample PL/SQL statement retrieves the FIRST_NAME and DEPARTMENT_ID from
the table. If you have to manipulate the FIRST_NAME or the DEPARTMENT_ID, then you
have to store the retrieved value.
SELECT
first_name,
department_id
INTO
v_fname,
v_deptno
FROM
Variables are used to store values temporarily. You can use the values stored in these
variables for processing and manipulating data.
Variables can store any PL/SQL object, such as variables, types, cursors, and
subprograms.
Reusability 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 requirements for variable names are that they

must start with a letter

can include letters or numbers

can include special characters such as $, _, and #

must contain no more than 30 characters

must not include reserved words


You can use variables in various ways:

declare and initialize variables in the declaration section

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

pass variables as parameters to PL/SQL subprograms

use variables to hold the output of a PL/SQL subprogram


declare and initialize variables in the declaration section
One way of using variables is to declare and initialize them in the declaration section. You
can declare variables in the declarative part of any PL/SQL block, subprogram, or
package. 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 NOT NULL constraint on the variable. Forward references are not
allowed. You must declare a variable before referencing it in other statements, including
other declarative statements.
use variables and assign new values to them in the executable section
You can use variables and assign new values to them in the executable section. In this
section, the existing value of the variable can be replaced with the new value.
pass variables as parameters to PL/SQL subprograms
Subprograms can take parameters. You can pass variables as parameters to
subprograms.
use variables to hold the output of a PL/SQL subprogram
You can use variables to hold the output of a PL/SQL subprogram that is returned by a
function.

Question
Which are true statements about variable name assignment?
Options:
1.

Variables may contain any number of characters as long as their length is defined

2.

Variables may include special characters

3.

Variables may start with either letters or numbers, but not special characters

4.

Variables must not include reserved words

Answer
Variables may include special characters and must not include reserved words.
Option 1 is incorrect. Variables have a maximum length of 30 characters. The
variable can have its length assigned to it, but the name itself must be 30
characters or less.
Option 2 is correct. Variables names may include letters, numbers, and special
characters.
Option 3 is incorrect. Variables names must always begin with a letter. Numbers
or special characters are not permitted at the beginning of any variable name.
Option 4 is correct. Variables may not use reserved words, such as MODIFY, ADD,
or ALL. These words are reserved by Oracle and have a specific function.

2. Declaring and initializing variables


You must declare all PL/SQL identifiers in the declaration section before referencing them
in the PL/SQL block.
This is the syntax for declaring a PL/SQL identifier.
identifier [CONSTANT] datatype [NOT NULL]
[:= | DEFAULT expr];
In the syntax, you can specify certain elements.

identifier

CONSTANT

datatype

NOT NULL

expr
identifier
identifier is the name of the variable.
CONSTANT
CONSTANT constrains the variable so that its value cannot change. Constants must be
initialized.
datatype
datatype is a scalar, composite, reference, or large object (LOB) data type.

NOT NULL
NOT NULL constrains the variable so that it must contain a value. NOT NULL variables
must be initialized.
expr
The expr is any PL/SQL expression that can be a literal expression, another variable, or
an expression involving operators and functions.
You have the option of assigning an initial value to a variable. You do not need to assign a
value to a variable in order to declare it. If 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 examples of declaring variables.
DECLARE
v_hiredate
v_deptno
v_location
c_comm

DATE;
NUMBER(2) NOT NULL := 10;
VARCHAR2(13) :='Atlanta';
CONSTANT NUMBER := 1400;

Note
In addition to variables, you can declare cursors and exceptions in the declarative
section.
Consider a sample code, in which a variable is declared in the declarative section but
initialized in the executable block of the code block.
In this code block, the v_myName variable is declared in the declarative section of the
block. This variable can be accessed in the executable section of the same block. A value
John is assigned to the variable in the executable section.
DECLARE
v_myName VARCHAR2(20);
BEGIN
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
v_myName := 'John';
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
END;
/
String literals must be enclosed in single quotation marks. If your string has a quotation
mark for example in "Today's Date" then the string would be "Today''s Date."
Note that there are two single quotation marks between y and s. ":=" is the assignment
operator. The PUT_LINE procedure is invoked by passing the v_myName variable. The
value of the variable is concatenated with the string 'My name is:'.

DECLARE
v_myName VARCHAR2(20);
BEGIN
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
v_myName := 'John';
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
END;
/
Consider another sample code, in which the v_myName variable is declared and
initialized in the declarative section. v_myName holds the value John after initialization.
This value is manipulated in the executable section of the block.
DECLARE
v_myName VARCHAR2(20):= 'John';
BEGIN
v_myName := 'Steven';
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
END;
/
If your string contains an apostrophe which is identical to a single quotation mark you
need to double the quotation mark.
The first quotation mark acts as the escape character. This makes your string
complicated, especially if you have SQL statements as strings. You can specify any
character that is not present in the string as delimiter.
v_event VARCHAR2(15):='Father''s day';
This sample code indicates the use of the q' notation to specify the delimiter. The
example uses ! and [ as delimiters.
DECLARE
v_event VARCHAR2(15);
BEGIN
v_event := q'!Father's day!';
DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is :
'|| v_event );
v_event := q'[Mother's day]';
DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is :
'|| v_event );
END;
/
In the first line of the code, two single quotation marks are used. You start the string with
q' if you want to use a delimiter, as in the second line of the code. The character

following the notation is the delimiter used.


You enter your string after specifying the delimiter, close the delimiter, and close the
notation with a single quotation mark.
v_event VARCHAR2(15):='Father''s day';
v_event := q'!Father's day!';
This sample code indicates the use of [ as a delimiter.
v_event := q'[Mother's day]';
Every PL/SQL variable has a data type, which specifies a storage format, constraints, and
a valid range of values.
PL/SQL supports these four data type categories, which you can use these data types to
declare variables, constants, and pointers:

scalar

composite

reference

LOB
scalar
Scalar data types hold a single value. The value depends on the data type of the variable.
For example, the v_myName variable in the code example is of type VARCHAR2. Therefore,
v_myName can hold a string value. PL/SQL also supports Boolean variables.
composite
Composite data types contain internal elements that are either scalar or composite.
RECORD and TABLE are examples of composite data types.
reference
Reference data types hold values, called pointers, which point to a storage location.
LOB
LOB data types hold values, called locators, which specify the location of large objects
such as graphic images that are stored outside the table.
Non-PL/SQL variables include host language variables declared in precompiler programs,
screen fields in Forms applications, and host variables.
Here are examples of different data types:

TRUE represents a Boolean value

25-JAN-01 represents a DATE

an image represents a BLOB

the text "Long, long ago, in a land far far away, there lived a princess called Snow White..." can
represent a VARCHAR2 data type or a CLOB

256120.08 represents a NUMBER data type with precision and scale

the film reel represents a BFILE

the city name Atlanta represents a VARCHAR2 data type


Here are some guidelines for declaring and initializing PL/SQL variables.

follow naming conventions

use meaningful and appropriate identifiers for variables

the CONSTANT keyword must precede the type specifier

initialize the variable to an expression

qualify objects with the same name with labels

do not use column names as identifiers

impose the NOT NULL constraint


follow naming conventions
When declaring variables, you should follow a naming convention. For example, use name
to represent a variable and c_name to represent a constant. Similarly, to name a variable,
you can use v_fname.
<code>
DECLARE
v_myName VARCHAR2(20);
BEGIN
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
v_myName := 'John';
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
END;
/
</code>
use meaningful and appropriate identifiers for variables
When declaring variables, you should use meaningful and appropriate identifiers for
variables. For example, consider using salary and sal_with_commission instead of
salary1 and salary2.
the CONSTANT keyword must precede the type specifier
In constant declarations, the CONSTANT keyword must precede the type specifier. The
sample code names a constant of NUMBER type and assigns the value of 50,000 to the
constant. A constant must be initialized in its declaration otherwise, you get a compilation
error. After initializing a constant, you cannot change its value.

<code>
sal CONSTANT NUMBER := 50000.00;
</code>
initialize the variable to an expression
Initialize the variable to an expression with the assignment operator := or with the
DEFAULT reserved word. If you do not assign an initial value, the new variable contains
NULL by default until you assign a value. To assign or reassign a value to a variable, you
write a PL/SQL assignment statement. It is good programming practice to initialize all
variables.
<code>
v_myName VARCHAR2(20):='John';
v_myName VARCHAR2(20) DEFAULT 'John';
</code>
qualify objects with the same name with labels
If two objects with the same name coexist, you can qualify them with labels and use them.
Otherwise two objects can have the same name only if they are defined in different blocks.
</code>
DECLARE
employee_id NUMBER(6);
BEGIN
SELECT employee_id
INTO employee_id
FROM employees
WHERE last_name = 'Kochhar';
END;
/
</code>
do not use column names as identifiers
Avoid using column names as identifiers. If PL/SQL variables occur in SQL statements and
have the same name as a column, the Oracle server assumes that it is the column that is
being referenced. Although the code works, code that is written using the same name for a
database table and a variable is not easy to read or maintain.
</code>
DECLARE
employee_id NUMBER(6);
BEGIN
SELECT employee_id
INTO employee_id
FROM employees
WHERE last_name = 'Kochhar';
END;

/
<./code>
impose the NOT NULL constraint
Impose the NOT NULL constraint when the variable must contain a value. If you use the
NOT NULL constraint, you must assign a value when you declare the variable. You cannot
assign nulls to a variable defined as NOT NULL. The NOT NULL constraint must be
followed by an initialization clause.
<code>
pincode VARCHAR2(15) NOT NULL := 'Oxford';
</code>

Question
Which statement about declaring and initializing PL/SQL variables is true?
Options:
1.

Constant variables cannot be changed

2.

Identifiers can be used without being declared in the declaration block

3.

Once declared, you must assign a value to a variable

4.

You may refer to undeclared variables in a declaration

Answer
When declaring and initializing PL/SQL variables, constant variables cannot be
changed.
Option 1 is correct. Constants must be initialized. Being initialized as a constant
constrains the variable so that its value cannot change dynamically.
Option 2 is incorrect. Identifiers must be declared in the initialization block before
being referenced. Values may be assigned prior to use.
Option 3 is incorrect. Even if a variable is declared, it is not mandatory to use. If
nothing references the variable in the executable section of the PL/SQL block, it
will simply not be used.
Option 4 is incorrect. Although you can use variables as part of the declaration of
another variable, you must ensure that the variable being referred to is declared
first. Otherwise, you will be referencing a variable that does not yet exist.

Question
Which statements are true about string delimiters?

Options:
1.

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

2.

The first single quotation mark in a set of two acts as an escape character

3.

The q' notation is used to specify a delimiter

4.

The second single quotation mark in a set of two acts as an escape character

Answer
The q' notation is used to specify a delimiter. The first single quotation mark in a
set of two acts as an escape character.
Option 1 is incorrect. The character following the notation is the delimiter used.
You enter your string after specifying the delimiter, close the delimiter, and close
the notation with a single quotation mark.
Option 2 is correct. If your string contains a single quotation mark, you must
double the quotation mark. The first quotation mark then acts as the escape
character.
Option 3 is correct. The q' notation is used to specify a delimiter. For example,
with q'! Sample text!', the ! character serves as the escape character.
Option 4 is incorrect. The first single quotation mark serves as an escape
character if two are encountered. This is most commonly used when an
apostrophe is part of the string for example, "Shelley's". To properly display the
string, you would need to type "Shelley''s" within the string.

Summary
You can declare variables and then use them in SQL and procedural statements. You can
use the values stored in these variables for processing and manipulating data. A variable
name must start with a letter. It can include letters, numbers, and special characters. It
must not contain more than 30 characters or reserved words. You can use variables in
the declaration section, use them and assign new values to them in the executable
section, pass them as parameters to PL/SQL subprograms, and use them to hold the
output of a PL/SQL subprogram.
You must declare all PL/SQL identifiers in the declaration section before referencing them
in the PL/SQL block. String literals must be enclosed in single quotation marks. If your
string contains an apostrophe, you need to double the quotation mark. You can specify
any character that is not present in the string as a delimiter. The data types supported by
PL/SQL include scalar, composite, reference, and LOB.

Table of Contents

| Top of page |
| Learning objective |
| 1. Introducing variables |
| 2. Declaring and initializing variables |
| Summary |
Copyright 2008 SkillSoft. All rights reserved.
SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

| Print | Contents | Close |

Introducing PL/SQL Data Types and Attributes


Learning objective

After completing this topic, you should be able to identify the uses of different PL/SQL
data types, the %TYPE attribute, and BIND variables.

1. Using PL/SQL data types


PL/SQL provides a variety of predefined data types. For instance, you can choose from
integer, floating point, character, Boolean, date, collection, and large objects (LOB) types.
A scalar data type holds a single value and has no internal components. Scalar data
types can be classified into four categories: number, character, date, and Boolean.
Character and number data types have subtypes that associate a base type to a
constraint. For example, INTEGER and POSITIVE are subtypes of the NUMBER base
type.
These are some basic scalar data types:

CHAR [(maximum_length)]

VARCHAR2 (maximum_length)

NUMBER [(precision, scale)]

BINARY_INTEGER

PLS_INTEGER

BOOLEAN

BINARY_FLOAT

BINARY_DOUBLE
CHAR [(maximum_length)]
The CHAR data type is the base type for fixed-length character data up to 32,767 bytes. If
you do not specify a maximum length, the default length is set to 1.
VARCHAR2 (maximum_length)
The VARCHAR2 data type is the base type for variable-length character data up to 32,767
bytes. There is no default size for VARCHAR2 variables and constants.
NUMBER [(precision, scale)]
The NUMBER data type represents a number having precision p and scale s. The precision
p can range from 1 through 38. The scale s can range from -84 through 127.
BINARY_INTEGER
The BINARY_INTEGER data type is the base type for integers between
-2,147,483,647 and 2,147,483,647.
PLS_INTEGER
The PLS_INTEGER data type is the base type for signed integers between
-2,147,483,647 and 2,147,483,647. PLS_INTEGER values require less storage and are
faster than NUMBER values. In Oracle Database 10g, the PLS_INTEGER and
BINARY_INTEGER data types are identical. The arithmetic operations on PLS_INTEGER
and BINARY_INTEGER values are faster than on NUMBER values.
BOOLEAN
The BOOLEAN data type is the base type that stores one of the three possible values used
for logical calculations: TRUE, FALSE, and NULL.
BINARY_FLOAT
The BINARY_FLOAT data type represents floating-point number in IEEE 754 format. It
requires 5 bytes to store the value.
BINARY_DOUBLE
The BINARY_DOUBLE represents floating-point number in IEEE 754 format. It requires 9
bytes to store the value.
Some more basic scalar data types include

DATE

TIMESTAMP

TIMESTAMP WITH TIME ZONE

TIMESTAMP WITH LOCAL TIME ZONE

INTERVAL YEAR TO MONTH

INTERVAL DAY TO SECOND


DATE

The DATE data type is the base type for dates and times. DATE values include the time of
day in seconds since midnight. The range for dates is between 4712 B.C. and A.D. 9999.
TIMESTAMP
The TIMESTAMP data type, which extends the DATE data type, stores the year, month,
day, hour, minute, second, and fraction of second. The syntax is
TIMESTAMP[(precision)], where the optional parameter precision specifies the
number of digits in the fractional part of the seconds field. To specify the precision, you
must use an integer in the range 0-9. The default is 6.
TIMESTAMP WITH TIME ZONE
The TIMESTAMP WITH TIME ZONE data type, which extends the TIMESTAMP data type,
includes a time-zone displacement. The time-zone displacement is the difference (in hours
and minutes) between local time and Coordinated Universal Time (UTC), formerly known
as Greenwich Mean Time.
The syntax for this data type is TIMESTAMP[(precision)] WITH TIME ZONE, where
the optional parameter precision specifies the number of digits in the fractional part of
the seconds field. To specify the precision, you must use an integer in the range 0-9.
The default is 6.
TIMESTAMP WITH LOCAL TIME ZONE
The TIMESTAMP WITH LOCAL TIME ZONE data type, which extends the TIMESTAMP
data type, includes a time-zone displacement. The time-zone displacement is the
difference (in hours and minutes) between local time and Coordinated Universal Time
(UTC), formerly known as Greenwich Mean Time.
The syntax for this data type is TIMESTAMP[(precision)] WITH LOCAL TIME ZONE,
where the optional parameter precision specifies the number of digits in the fractional
part of the seconds field. You cannot use a symbolic constant or variable to specify the
precision you must use an integer literal in the range 0-9. The default is 6.
INTERVAL YEAR TO MONTH
You use the INTERVAL YEAR TO MONTH data type to store and manipulate intervals of
years and months.
The syntax for this data type is INTERVAL YEAR[(precision)] TO MONTH, where
precision specifies the number of digits in the years field. You cannot use a symbolic
constant or variable to specify the precision you must use an integer literal in the
range 0-4. The default is 2.
INTERVAL DAY TO SECOND
You use the INTERVAL DAY TO SECOND data type to store and manipulate intervals of
days, hours, minutes, and seconds.
The syntax for this data type is INTERVAL DAY[(precision1)] TO

SECOND[(precision2)], where precision1 and precision2 specify the number of


digits in the days field and seconds field, respectively. In both cases, you cannot use a
symbolic constant or variable to specify the precision you must use an integer literal
in the range 0-9. The defaults are 2 and 6, respectively.
The TIMESTAMP WITH LOCAL TIME ZONE data type differs from the TIMESTAMP
WITH TIME ZONE data type in that when you insert a value into a database column, the
value is normalized to the database time zone, and the time-zone displacement is not
stored in the column. When you retrieve the value, the Oracle server returns the value in
your local session time zone.
Here are some examples of variable declarations:

v_emp_job

v_count_loop

v_dept_total_sal

v_orderdate

c_tax_rate

v_valid
v_emp_job
v_emp_job is a variable to store an employee job title.
<code>
DECLARE
v_emp_job VARCHAR2(9);
</code>
v_count_loop
v_count_loop is a variable to count the iterations of a loop; initialized to 0.
<code>
v_count_loop BINARY_INTEGER := 0;
</code>
v_dept_total_sal
v_dept_total_sal is a variable to accumulate the total salary for a department;
initialized to 0.
<code>
v_dept_total_sal NUMBER(9,2) := 0;
</code>
v_orderdate
v_orderdate is a variable to store the ship date of an order; initialized to one week from
today.
<code>

v_orderdate DATE := SYSDATE + 7;


</code>
c_tax_rate
c_tax_rate is a constant variable for the tax rate, which never changes throughout the
PL/SQL block set to 8.25.
<code>
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
</code>
v_valid
v_valid is a flag to indicate whether a piece of data is valid or invalid; initialized to TRUE.
<code>
v_valid BOOLEAN NOT NULL := TRUE;
...
</code>
PL/SQL variables are usually declared to hold and manipulate data stored in a database.
When you declare PL/SQL variables to hold column values, you must ensure that the
variable is of the correct data type and precision. If it is not, a PL/SQL error occurs during
execution. If you have to design large subprograms, this can be time consuming and error
prone.
Rather than hard coding the data type and precision of a variable, you can use the %TYPE
attribute to declare a variable according to another previously declared variable or
database column. The %TYPE attribute is most often used when the value stored in the
variable is derived from a table in the database. When you use the %TYPE attribute to
declare a variable, you should prefix it with the database table and column name. If you
refer to a previously declared variable, prefix the variable name of the previously declared
variable to the variable being declared.
These are some advantages of the %TYPE attribute:

helps avoid data type mismatch errors

helps avoid data type hard coding

ensures variable and column compatibility


helps avoid data type mismatch errors
By using the %TYPE attribute, you can avoid errors caused by data type mismatch or
wrong precision.
helps avoid data type hard coding
By using the %TYPE attribute, you can avoid hard coding the data type of a variable.
ensures variable and column compatibility

The %TYPE attribute ensures compatibility of a variable with the column. Using the %TYPE
attribute, you need not change the variable declaration if the column definition changes. If
you have already declared some variables for a particular table without using the %TYPE
attribute, the PL/SQL block may throw errors if the column for which the variable is
declared is altered. When you use the
%TYPE attribute, PL/SQL determines the data type and size of the variable when the block
is compiled. This ensures that the variable is always compatible with the column that is
used to populate it.
This is the syntax for declaring variables with the %TYPE attribute.
identifier table.column_name%TYPE;
This sample code declares variables to store the last name of an employee. The
emp_lname variable is defined to be of the same data type as the last_name column in
the EMPLOYEES table. The %TYPE attribute provides the data type of a database column.
...
emp_lname employees.last_name%TYPE;
...
Here is a sample code that declares variables to store the balance of a bank account, as
well as the minimum balance, which is 1,000. The min_balance variable is defined to
be of the same data type as the balance variable. The %TYPE attribute provides the data
type of a variable.
...
balance NUMBER(7,2);
min_balance balance%TYPE := 1000;
...
A NOT NULL database column constraint does not apply to variables that are declared
using %TYPE. Therefore, if you declare a variable using the %TYPE attribute that uses a
database column defined as NOT NULL, you can assign the NULL value to the variable.
With PL/SQL, you can compare variables in both SQL and procedural statements. These
comparisons, called Boolean expressions, consist of simple or complex expressions
separated by relational operators.
In a SQL statement, you can use Boolean expressions to specify the rows in a table that
are affected by the statement. In a procedural statement, Boolean expressions are the
basis for conditional control. NULL stands for a missing, inapplicable, or unknown value.
When declaring Boolean variables

only the TRUE, FALSE, and NULL values can be assigned to a Boolean variable
conditional expressions use the logical operators AND and OR and the unary operator NOT to
check the variable values

the variables always yield TRUE, FALSE, or NULL

arithmetic, character, and date expressions can be used to return a Boolean value
In this sample, the Boolean expression yields TRUE.
emp_sal1 := 50,000;
emp_sal2 := 60,000;
emp_sal1 < emp_sal2
In this sample, the Boolean variable is declared and intialized.
DECLARE
flag BOOLEAN := FALSE;
BEGIN
flag := TRUE;
END;
/

Question
Which is not a base scalar data type?
Options:
1.

BOOLEAN

2.

BINARY_FLOAT

3.

LOB

4.

PLS_INTEGER

Answer
LOB is not a base scalar data type.
Option 1 is incorrect. BOOLEAN is a base scalar type that stores one of the three
possible values used for logical calculations TRUE, FALSE, and NULL.
Option 2 is incorrect. BINARY_FLOAT is a base scalar type that represents
floating-point number in IEEE 754 format. It requires 5 bytes to store the value.
Option 3 is correct. LOBs are for storing a large amount of data. A database
column can be of the LOB category. LOBs are not scalar types.

Option 4 is incorrect. PLS_INTEGER is a base scalar type for signed integers


between -2,147,483,647 and 2,147,483,647.

Question
Which are true statements about using BOOLEAN variables?
Options:
1.

BOOLEAN can be used concurrently with conditional expressions

2.

BOOLEAN may not be used concurrently with expressions performing arithmetic


operations

3.

BOOLEAN values may be reset after they have been set as a result of a comparison

4.

BOOLEAN will only return TRUE or FALSE

Answer
BOOLEAN can be used concurrently with conditional expressions and BOOLEAN
values may be reset after they have been set as a result of a comparison.
Option 1 is correct. Conditional expressions use the logical operators AND and OR
and the unary operator NOT to check the BOOLEAN variable values.
Option 2 is incorrect. Arithmetic, character, and date expressions can be used to
return a Boolean value. For example, the statement variable_a <>
variable, tests inequality. If the two variables are unequal, it will return TRUE.
Option 3 is correct. If a BOOLEAN comparison returns a value of FALSE, at any
point afterward in the PL/SQL block, it can be reset to TRUE. This is especially
useful for a block of code that needs to be rerun or re-evaluated when multiple
records are being processed.
Option 4 is incorrect. BOOLEAN can return the value NULL, as well as TRUE or
FALSE.

2. Using bind variables and LOB data types


Bind variables are variables that you create in a host environment. For this reason, they
are sometimes called host variables.
Bind variables are created in the environment and not in the declarative section of a
PL/SQL block. Variables declared in a PL/SQL block are available only when you execute
the block. After the block is executed, the memory used by the variable is freed.

However, bind variables are accessible even after the block is executed. Therefore, when
created, bind variables can be used and manipulated by multiple subprograms. They can
be used in SQL statements and PL/SQL blocks just like any other variable. These
variables can be passed as run-time values into or out of PL/SQL subprograms.
To create a bind variable in SQL Developer, you use the VARIABLE command.
For example, you declare a variable of type NUMBER and VARCHAR2.
VARIABLE return_code NUMBER
VARIABLE return_msg VARCHAR2(30)
SQL Developer can reference the bind variable and can display its value through the
PRINT command. You can reference a bind variable in a PL/SQL program by preceding
the variable with a colon.
VARIABLE b_result NUMBER
BEGIN
SELECT (SALARY*12) + NVL(COMMISSION_PCT,0) INTO :b_result
FROM employees WHERE employee_id = 144;
END;
/
PRINT b_result
b_result
---------30000

Note
If you are creating a bind variable of the NUMBER type, you cannot specify the
precision and scale. However, you can specify the size for character strings. An
Oracle NUMBER is stored in the same way regardless of the dimension. The Oracle
server uses the same number of bytes to store 7, 70, and .0734. It is not practical
to calculate the size of the Oracle number representation from the number format,
so the code always allocates the bytes needed. With character strings, the size is
required from the user so that the required number of bytes can be allocated.
In SQL*Plus, you can display the value of a bind variable by using the PRINT command.
When you execute this PL/SQL block, you get this output when the PRINT command
executes.
VARIABLE b_emp_salary NUMBER
BEGIN
SELECT salary INTO :b_emp_salary

FROM employees WHERE employee_id = 178;


END;
/
PRINT b_emp_salary
SELECT first_name, last_name FROM employees
WHERE salary=:b_emp_salary;
In the output, b_emp_salary is a bind variable. You can now use this variable in any
SQL statement or PL/SQL program. Note the SQL statement in the code that uses the
bind variable. This is the output of the SQL statement.
VARIABLE b_emp_salary NUMBER
BEGIN
SELECT salary INTO :b_emp_salary
FROM employees WHERE employee_id = 178;
END;
/
PRINT b_emp_salary
SELECT first_name, last_name FROM employees
WHERE salary=:b_emp_salary;
b_emp_salary
-----------------7000
FIRST_NAME
-----------------Oliver
Sarath
Kimberely

LAST_NAME
---------------------Tuvault
Sewall
Grant

Note
To display all bind variables, use the PRINT command without a variable.
You use the SET AUTOPRINT ON command to automatically display the bind variables
used in a successful PL/SQL block.
VARIABLE b_emp_salary NUMBER
SET AUTOPRINT ON
DECLARE
v_empno NUMBER(6):=&empno;
BEGIN
SELECT salary INTO :b_emp_salary
FROM employees WHERE employee_id = v_empno;
END;

b_emp_salary
-----------------7000
LOBs are meant to store a large amount of data. A database column can be of the LOB
category.
With the LOB category of data types, you can store blocks of unstructured data such as
text, graphic images, video clips, and sound wave forms, of up to 128 terabytes
depending on the database block size. LOB data types allow efficient, random, and
piecewise access to the data and can be attributes of an object type.
These are some LOB data types:

CLOB

BLOB

BFILE

NCLOB
CLOB
The character large object (CLOB) data type is used to store large blocks of character data
in the database.
BLOB
The binary large object (BLOB) data type is used to store large unstructured or structured
binary objects in the database. When you insert or retrieve such data into or from the
database, the database does not interpret the data. External applications that use this data
must interpret the data.
BFILE
The binary file (BFILE) data type is used to store large binary files. Unlike other LOBs,
BFILES are not stored in the database. BFILEs are stored outside the database. They
could be operating system files. Only a pointer to the BFILE is stored in the database.
NCLOB
The national language character large object (NCLOB) data type is used to store large
blocks of single-byte or fixed-width multibyte NCHAR Unicode data in the database.
A scalar type has no internal components. A composite type has internal components that
can be manipulated individually.
Composite data types, also known as collections, include TABLE, RECORD, NESTED
TABLE, and VARRAY types.

You use the TABLE data type to reference and manipulate collections of data as a whole
object.
You use the RECORD data type to treat related but dissimilar data as a logical unit.

Question
Which statements describe the proper use of LOB data types?
Options:
1.

BFILE types are used to store large amounts of data within the actual database,
such as video clips or movies

2.

BLOB types store large amounts of binary data, such as an image

3.

CLOB types can store any sort of character data, including foreign languages and
symbols

4.

NCLOB is used to store fixed width character data, including foreign languages and
symbols

Answer
BLOB types store large amounts of binary data such as an image. NCLOB is used
to store fixed width character data, including foreign languages and symbols.
Option 1 is incorrect. Although large data types such as movie clips could be
stored as type BFILE, they are stored on a file system and not in the database. A
pointer to the BFILE location is stored in the database.
Option 2 is correct. The BLOB data type is used to store large unstructured or
structured binary objects in the database, such as an image.
Option 3 is incorrect. Although the CLOB data types are used to store large blocks
of character data in the database, they are not compatible with all character types.
Option 4 is correct. The NCLOB data type is used to store large blocks of singlebyte or fixed-width multibyte NCHAR Unicode data in the database. Language
character sets such as Japanese, for example, would be stored as this type.

Summary
PL/SQL provides a variety of predefined data types such as integer, floating point,
character, Boolean, date, collection, and LOB. A scalar data type holds a single value and
has no internal components. Scalar data types can be categorized into number,
character, date, and Boolean. You can use the %TYPE attribute to declare a variable
according to another previously declared variable or database column. With PL/SQL, you

can also compare variables in both SQL and procedural statements using Boolean
expressions.
Bind variables are variables that you create in a host environment. To create a bind
variable in SQL Developer, you use the VARIABLE command. LOBs are meant to store a
large amount of data and allow efficient, random, and piecewise access to the data and
can be attributes of an object type. Some LOB data types include CLOB, BLOB, BFILE,
and NCLOB.

Table of Contents
| Top of page |
| Learning objective |
| 1. Using PL/SQL data types |
| 2. Using bind variables and LOB data types |
| Summary |
Copyright 2008 SkillSoft. All rights reserved.
SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

| Print | Contents | Close |

Writing Executable Statements


Learning objective

After completing this topic, you should be able to identify the steps for constructing
executable statements using various PL/SQL block elements.

1. Understanding lexical units


Lexical units are building blocks of any PL/SQL block and include letters, numerals,
special characters, tabs, spaces, returns, and symbols. Lexical units can be classified as

identifiers

delimiters

literals

comments

Identifiers are the names given to PL/SQL objects. Quoted identifiers allow you to

make identifiers case sensitive

include characters such as spaces

use reserved words

Note
Keywords cannot be used as identifiers.
Here are some examples of quoted identifiers. All subsequent usage of these variables
should have double quotation marks. However, use of quoted identifiers is not
recommended.
"begin date" DATE;
"end date" DATE;
"exception thrown" BOOLEAN DEFAULT TRUE;
Delimiters are simple or compound symbols that have special meaning in PL/SQL.
Semicolon (;) is an example of a delimiter that is used to terminate a SQL or PL/SQL
statement. The tables display a list of simple and compound symbols.

Supplement
Selecting the link title opens the resource in a new browser window.

Launch window
View the tables for simple symbols and compound symbols.

Note
The list of symbols is only a subset and not a complete list of delimiters.
A literal is any value that is assigned to a variable. A literal is an explicit numeric,
character string, date, or Boolean value that is not represented by an identifier.
Literals are classified as

character literals

numeric literals

Boolean literals
character literals

All string literals have the data type CHAR or VARCHAR2 and are therefore, called character
literals. For example John and 12C. Character literals include all the printable characters
in the PL/SQL character set such as letters, numerals, spaces, and special symbols.
numeric literals
A numeric literal represents an integer or real value - for example, 428 and 1.276. It can
be represented either by a simple value such as 32.5 or in scientific notation - for
example, 2E5 means 2 * 10^5 = 200,000.
Boolean literals
Values that are assigned to Boolean variables are Boolean literals. TRUE, FALSE, and
NULL are Boolean literals or keywords.
It is good programming practice to explain what a piece of code is trying to achieve.
When you include the explanation in a PL/SQL block, the compiler cannot interpret these
instructions. There should be a way in which you can indicate that these instructions need
not be compiled. Comments are mainly used for this purpose. Any instruction that is
commented is not interpreted by the compiler. You can specify comments using

two hyphens (--) to comment a single line

the beginning and ending comment delimiters (/* and */) to comment multiple lines
You should comment code to document each phase and to assist debugging. Comments
are strictly informational and do not enforce any conditions or behavior on the logic or
data. Well-placed comments are extremely valuable for code readability and future code
maintenance. In this sample code, the lines enclosed within /* and */ indicate a multiple
line comment that explains the code. The line that starts with -- indicates a single line
comment.
DECLARE
...
v_annual_sal NUMBER (9,2);
BEGIN
/* Compute the annual salary based on the
monthly salary input from the user */
v_annual_sal := monthly_sal * 12;
--The following line displays the annual salary
DBMS_OUTPUT.PUT_LINE(v_annual_sal);
END;
/
These are some guidelines for PL/SQL block:

character and date literals must be enclosed in single quotation marks

numbers can be simple values or in scientific notation

a statement can span several lines

you can format an unformatted SQL statement by right-clicking the active SQL worksheet and
selecting the Format SQL option in SQL Developer

2. Using SQL functions and conversions


SQL provides several predefined functions that can be used in SQL statements. Most of
these functions are valid in PL/SQL expressions:

single-row number and character functions

data type conversion functions

date and time-stamp functions


These functions are not available in procedural statements:

DECODE

group functions such as AVG, MIN, MAX, COUNT, SUM, STDDEV, and VARIANCE
Group functions apply to groups of rows in a table and are, therefore, available only in
SQL statements in a PL/SQL block. The functions mentioned here are only a subset of
the complete list.
You can use SQL functions to manipulate data. These functions are grouped into these
categories:

number

character

conversion

date

miscellaneous
In this sample code, the LENGTH SQL function is used to get the length of a string.
v_desc_size INTEGER(5);
v_prod_description VARCHAR2(70):='You can use this
product with your radios for higher frequency';
-- get the length of the string in prod_description
v_desc_size:= LENGTH(prod_description);
In this sample code, the MONTHS_BETWEEN SQL function is used to get the number of
months an employee has worked.
v_tenure:= MONTHS_BETWEEN (CURRENT_DATE, v_hiredate);

In Oracle Database 11g, you can use the NEXTVAL and CURRVAL pseudo-columns in any
PL/SQL context where an expression of NUMBER data type may legally appear. Although
the old style of using a SELECT statement to query a sequence is still valid, it is
recommended that you do not use it.
DECLARE
v_new_id NUMBER;
BEGIN
v_new_id := my_seq.NEXTVAL;
END;
/
Before Oracle Database 11g, you were forced to write a SQL statement in order to use a
sequence object value in a PL/SQL subroutine. Typically, you write a SELECT statement
to reference the pseudo-columns of NEXTVAL and CURRVAL to obtain a sequence
number. This method created a usability problem.
DECLARE
v_new_id NUMBER;
BEGIN
SELECT my_seq.NEXTVAL INTO v_new_id FROM Dual;
END;
/
In Oracle Database 11g, the limitation of forcing you to write a SQL statement to retrieve
a sequence value is lifted. With the sequence enhancement feature

sequence usability is improved

less typing is required by the developer

the resulting code is clearer


In any programming language, converting one data type to another is a common
requirement. Data type conversion involves converting data to comparable data types.
PL/SQL can handle such conversions with scalar data types.
Data type conversions can be of these two types:

implicit

explicit
implicit
In an implicit conversion, PL/SQL attempts to convert data types dynamically if they are
mixed in statement. Implicit conversions can be between

characters and numbers

characters and dates

explicit
An explicit conversion converts values from one data type to another using built-in
functions. For example, to convert a CHAR value to a DATE or NUMBER value, use
TO_DATE or TO_NUMBER, respectively.
Consider this sample code for implicit conversions. In this code, the sal_hike variable is
of the VARCHAR2 type. When calculating the total salary, PL/SQL first converts sal_hike
to NUMBER and then performs the operation. The result is of the NUMBER type.
DECLARE
v_salary NUMBER(6):=6000;
v_sal_hike VARCHAR2(5):='1000';
v_total_salary v_salary%TYPE;
BEGIN
v_total_salary:=v_salary + v_sal_hike;
END;
Here are three examples of implicit and explicit conversions of the DATE data type.
In the first example, because the string literal being assigned to date_of_joining is in
the default format, this example performs implicit conversion and assigns the specified
date to date_of_joining.
In the second example, PL/SQL returns an error because the date that is being assigned
is not in the default format.
In the third example, the TO_DATE function is used to explicitly convert the given date in a
particular format and assign it to the DATE data type variable date_of_joining.
//Example 1
date_of_joining DATE:= '02-Feb-2000';
//Example 2
date_of_joining DATE:= 'February 02,2000';
//Example 3
date_of_joining DATE:= TO_DATE('February
02,2000','Month DD, YYYY');

Question
Which are true statements about data type conversion in PL/SQL?
Options:

1.

An explicit conversion would be required to convert a string to number format

2.

Characters can be converted to dates implicitly

3.

Implicit conversions take place when PL/SQL attempts to convert data types via the
use of built-in functions

4.

PL/SQL converts data to comparable data types

Answer
Characters can be converted to dates implicitly and PL/SQL converts data to
comparable data types.
Option 1 is incorrect. An explicit conversion would not be required. PL/SQL
attempts to convert data types dynamically if they are mixed in a statement. For
example, if you try to add a VARCHAR2 value to a numeric value, where the
VARCHAR2 value represents a numeric value, this conversion takes place implicitly
without the use of functions.
Option 2 is correct. Characters can be converted to a DATE value implicitly when
the character data value represents a valid date value.
Option 3 is incorrect. It is explicit conversions that use built-in functions.
Option 4 is correct. PL/SQL can handle conversions with scalar data types either
implicitly or explicitly. Data types are converted to comparable data types.

3. Using nested blocks and operators


Being procedural gives PL/SQL the ability to nest statements. You can nest blocks
wherever an executable statement is allowed, thus making the nested block a statement.
If your executable section has code for many logically related functionalities to support
multiple business requirements, you can divide the executable section into smaller
blocks. The exception section can also contain nested blocks.
This is an example of a nested block. It has an outer (parent) block and a nested (child)
block. The v_outer_variable variable is declared in the outer block and the
v_inner_variable variable is declared in the inner block.
DECLARE
v_outer_variable VARCHAR2(20):='GLOBAL VARIABLE';
BEGIN
DECLARE
v_inner_variable VARCHAR2(20):='LOCAL VARIABLE';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_inner_variable);
DBMS_OUTPUT.PUT_LINE(v_outer_variable);

END;
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
The nested block example consists of these two variables:

v_outer_variable

v_inner_variable
v_outer_variable
The v_outer_variable variable is local to the outer block but global to the inner block.
When you access this variable in the inner block, PL/SQL first looks for a local variable in
the inner block with that name. There is no variable with the same name in the inner block,
so PL/SQL looks for the variable in the outer block. Therefore, v_outer_variable is
considered to be the global variable for all the enclosing blocks. You can access this
variable in the inner block. Variables declared in a PL/SQL block are considered local to
that block and global to all its subblocks.
v_inner_variable
The v_inner_variable variable is local to the inner block and is not global because the
inner block does not have any nested blocks. This variable can be accessed only within
the inner block. If PL/SQL does not find the variable declared locally, it looks upward in the
declarative section of the parent blocks. PL/SQL does not look downward in the child
blocks.
Here is a sample code that depicts the use of nested blocks and its output.
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
v_date_of_birth DATE:='12-Dec-2002';
BEGIN
DBMS_OUTPUT.PUT_LINE('Father''s Name: '||v_father_name);
DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth);
DBMS_OUTPUT.PUT_LINE('Child''s Name: '||v_child_name);
END;
DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth);
END;
The scope of a variable is the portion of the program in which the variable is declared and
is accessible. In the code, variable scope includes

v_father_name and v_date_of_birth

v_child_name and v_date_of_birth


v_father_name and v_date_of_birth
The v_father_name and v_date_of_birth variables are declared in the outer block.
These variables have the scope of the block in which they are declared and are
accessible. Therefore, the scope of these variables is limited to the outer block.
v_child_name and v_date_of_birth
The v_child_name and v_date_of_birth variables are declared in the inner block or
the nested block. These variables are accessible only within the nested block and are not
accessible in the outer block. When a variable is out of scope, PL/SQL frees the memory
used to store the variable therefore, these variables cannot be referenced.
The visibility of a variable is the portion of the program where the variable can be
accessed without using a qualifier.
The v_date_of_birth variable declared in the outer block has scope even in the inner
block. However, this variable is not visible in the inner block because the inner block has
a local variable with the same name.
In the sample code

Examine the code in the executable section of the PL/SQL block. You can print the father's name,
the child's name, and the date of birth. Only the child's date of birth can be printed here because
the father's date of birth is not visible.
The father's date of birth is visible in the code and, therefore, can be printed.
You cannot have variables with the same name in a block. However, you can declare
variables with the same name in two different blocks (nested blocks). The two items
represented by the identifiers are distinct and changes in one do not affect the other.
A qualifier is a label given to a block. You can use a qualifier to access the variables that
have scope but are not visible. In this sample code, you can now print the father's date of
birth and the child's date of birth in the inner block. The outer block is labeled outer. You
can use this label to access the v_date_of_birth variable declared in the outer block.
Because labeling is not limited to the outer block, you can label any block.
BEGIN <<outer>>
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
v_date_of_birth DATE:='12-Dec-2002';
BEGIN

DBMS_OUTPUT.PUT_LINE('Father''s Name: '||v_father_name);


DBMS_OUTPUT.PUT_LINE('Date of Birth: '
||outer.v_date_of_birth);
DBMS_OUTPUT.PUT_LINE('Child''s Name: '||v_child_name);
DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth);
END;
END;
END outer;
This is the output of running the previous nested block code example.
-- Output
anonymous block completed
Father's Name: Patrick
Date of Birth: 20-Apr-72
Child's Name: Mike
Date of Birth: 12-Dec-02
The operations in an expression are performed in a particular order depending on their
precedence or priority. Some operators in PL/SQL, as in SQL include

logical

arithmetic

concatenation

parentheses to control order of operations

exponential operator
Here is a table that shows the default order of operations from high priority to low priority.

Supplement
Selecting the link title opens the resource in a new browser window.

Launch window
View the table for the default order of operations from high priority to low priority.
Here are some examples of using operators in PL/SQL:
1. the + arithemetic operator is used to increment the counter for a loop
2. the AND logical operator and the BETWEEN comparison operator are used to set the
value of a Boolean flag

3. the IS NOT NULL comparsion operator is used to validate whether an employee


number contains a value
//Example 1
loop_count := loop_count + 1;
//Example 2
good_sal := sal BETWEEN 50000 AND 150000;
//Example 3
valid := (empno IS NOT NULL);
When working with nulls, you can avoid some common mistakes by keeping in mind
these rules:

comparisons involving nulls always yield NULL

applying the logical operator NOT to a null yields NULL

in conditional control statements, if the condition yields NULL, its associated sequence of
statements is not executed
To produce clear code and reduce maintenance when developing a PL/SQL block, you
need to consider

code conventions

indentation of code
This table provides guidelines for writing code in uppercase or lowercase characters to
help distinguish keywords from named objects.

Supplement
Selecting the link title opens the resource in a new browser window.

Launch window
View the table for guidelines for writing code in uppercase or lowercase
characters.
For 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.
//Example 1
BEGIN
IF x=0 THEN

y:=1;
END IF;
END;
/
//Example 2
DECLARE
deptno NUMBER(4);
location_id NUMBER(4);
BEGIN
SELECT department_id,
location_id
INTO
deptno,
location_id
FROM
departments
WHERE department_name
= 'Sales';
...
END;
/
Consider these two IF statements for readability.
IF x>y THEN max:=x;ELSE max:=y;END IF;
IF x > y THEN
max := x;
ELSE
max := y;
END IF;

Question
Which statements best describe the functionality of nested blocks?
Options:
1.

Exception sections may not contain nested blocks

2.

PL/SQL first looks to the inner block for a given variable name when it is being
accessed in the inner block

3.

Variables declared in a PL/SQL block are considered global to all blocks

4.

You can nest blocks wherever an executable statement is allowed

Answer

You can nest blocks wherever an executable statement is allowed. PL/SQL first
looks to the inner block for a given variable name when it is being accessed in the
inner block.
Option 1 is incorrect. You can nest blocks wherever an executable statement is
allowed, and the exception section can also contain nested blocks.
Option 2 is correct. When you access a given variable in the inner block, PL/SQL
first looks for a local variable in the inner block with that name. If there is no
variable with the same name in the inner block, PL/SQL looks for the variable in
the outer block.
Option 3 is incorrect. Variables declared in a PL/SQL block are considered local to
that block and global to all its sub blocks.
Option 4 is correct. You can nest blocks wherever an executable statement is
allowed, thus making the nested block a statement. If your executable section has
code for much logically related functionality to support multiple business
requirements, you can divide the executable section into smaller blocks.

Question
Identify the best practices in PL/SQL programming that are used to improve code
clarity and readability.
Options:
1.

Code should not be indented

2.

Database and column names should be in lower case

3.

Data types should be declared in upper case

4.

Keywords should always be in lower case

Answer
Data types should be declared in upper case and database and column names
should always in lower case.
Option 1 is incorrect. For 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.
Option 2 is correct. Database and column names such as EMPLOYEES,
EMPLOYEE_ID, and DEPARTMENT_ID should always be in lower case when used
in code.

Option 3 is correct. Data types should always be in upper case. For example,
VARCHAR2 and BOOLEAN are declared in upper case.
Option 4 is incorrect. PL/SQL key words such as DECLARE, BEGIN, and IF should
always be in upper case.

Summary
Lexical units are building blocks of any PL/SQL. It includes identifiers, delimiters, literals,
and comments. Identifiers are the names given to PL/SQL objects. Delimiters are
symbols that have special meaning in PL/SQL. A literal is any value that is assigned to a
variable. Comments indicate that instructions need not be compiled.
SQL provides the single-row number and character, data type conversion, and date and
time-stamp functions. The DECODE and group functions are not available in procedural
statements. Conversion functions convert a value from one data type to another and can
be implicit and explicit conversion.
PL/SQL enables you to nest statements wherever an executable statement is allowed,
thus making the nested block a statement. You can use comparison operators to
compare one expression to another. The result is always TRUE, FALSE, or NULL.

Table of Contents
| Top of page |
| Learning objective |
| 1. Understanding lexical units |
| 2. Using SQL functions and conversions |
| 3. Using nested blocks and operators |
| Summary |
Copyright 2008 SkillSoft. All rights reserved.
SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

| Print | Contents | Close |

Working with Executable Statements


Learning objective

After completing this topic, you should be able to evaluate a block of PL/SQL code with
respect to scoping and nesting rules, and write and test PL/SQL blocks.

Exercise overview
In this exercise, you are required to evaluate a block of PL/SQL code and determine the
data type and value of the specified variables. You are also required to identify the correct
code segments to meet specified requirements.
This involves the following tasks:

evaluating block scoping rules

evaluating block nesting rules

adding code for specific output


You are a database administrator for a company. As a part of your responsibilities, you
are required to retrieve and manipulate the data in the relational databases of the
company.

Task 1: Evaluating block scoping rules


One of your team members has written a PL/SQL code block that tracks the availability of
products in different locations of the company.
You need to evaluate this PL/SQL block to determine the data types and values of
variables according to the rules of scoping.
DECLARE
v_weight NUMBER(3) := 600;
v_message VARCHAR2(255) := 'Product 10012';
BEGIN
DECLARE
v_weight NUMBER(3) := 1;
v_message VARCHAR2(255) := 'Product 11001';
v_new_locn VARCHAR2(50) := 'Europe';
BEGIN
v_weight := v_weight + 1;
v_new_locn := 'Western ' || v_new_locn;
END;
v_weight := v_weight + 1;
v_message := v_message || ' is in stock';
v_new_locn := 'Western ' || v_new_locn;

END;
/

Supplement
Selecting the link title opens the resource in a new browser window.

Launch window
View this PL/SQL block of code to answer the upcoming questions.

Step 1 of 3
Identify the value and data type of the V_WEIGHT variable at position 1 of the
provided code.
Options:
1.

The value is 2 and the data type is NUMBER

2.

The value is 2 and the data type is VARCHAR2

3.

The value is 4 and the data type is NUMBER

4.

The value is 4 and the data type is VARCHAR2

Result
The value of the V_WEIGHT variable at position 1 of the code is 2 and its data type
is NUMBER.
Option 1 is correct. The variable V_WEIGHT is declared with a NUMBER data type
and is initialized with a value of 600. At position 1 of the provided code, the
V_WEIGHT variable has a NUMBER data type and a value of 2.
Option 2 is incorrect. The variable V_WEIGHT is declared with a NUMBER data type
and is initialized with a value of 600. At position 1 of the provided code, the data
type of V_WEIGHT is still NUMBER, but the value is 2.
Option 3 is incorrect. Although the data type of the V_WEIGHT variable is NUMBER,
its value at position 1 is 2.
Option 4 is incorrect. The variable V_WEIGHT is declared with a NUMBER data
type. At position 1 of the provided code, its value is 2, not 4.

Step 2 of 3

Identify the value and data type of the V_NEW_LOCN variable at position 1 of the
provided code.
Options:
1.

The value is Europe and the data type is VARCHAR2

2.

The value is is in stock and the data type is VARCHAR2

3.

The value is Product 11001 and the data type is VARCHAR2

4.

The value is Western Europe and the data type is VARCHAR2

Result
The value of the V_NEW_LOCN variable at position 1 of the provided code is
Western Europe and its data type is VARCHAR2.
Option 1 is incorrect. The variable V_NEW_LOCN is declared with a VARCHAR2
data type and is initialized with a value Europe. At position 1 of the provided
code, the value of this variable is Western Europe.
Option 2 is incorrect. The V_NEW_LOCN variable is declared with a VARCHAR2
data type. However, at no point in the provided code is the value of this variable
is in stock.
Option 3 is incorrect. The V_NEW_LOCN variable is declared with a VARCHAR2
data type. However, at no point in the provided code is the value of this variable
Product 11001.
Option 4 is correct. The variable V_NEW_LOCN is declared with a VARCHAR2 data
type. In the nested block of the provided code, the variable's initial value of
Europe is added to the string Western.

Step 3 of 3
Identify the value and data type of the V_WEIGHT variable at position 2 of the
provided code.
Options:
1.

The value is 601 and the data type is NUMBER

2.

The value is 10012 and the data type is NUMBER

3.

The value is Europe and the data type is VARCHAR2

4.

The value is Western Europe and the data type is VARCHAR2

Result

The value of the V_WEIGHT variable at position 2 of the provided code is 601 and
its data type is NUMBER.
Option 1 is correct. The variable V_WEIGHT is declared with a NUMBER data type
and is initialized with a value of 600. By position 2 of the provided code, 1 has
been added to the value of V_WEIGHT so that the value is 601.
Option 2 is incorrect. The variable V_WEIGHT is declared with a NUMBER data
type. Its initial value is 600, and by position 2 of the provided code, its value is
601. At no point in the provided code is the value of the V_WEIGHT variable
10012.
Option 3 is incorrect. The V_WEIGHT variable is declared with a NUMBER data
type. Therefore, Europe as a value would not be acceptable.
Option 4 is incorrect. The V_WEIGHT variable is declared with a NUMBER data
type. Therefore, Western Europe as a value would not be acceptable.

Task 2: Evaluating block nesting rules


One of your team members has written a PL/SQL code block that retrieves the credit
rating of different customers of the company.
You need to evaluate this PL/SQL block to determine the data types and values of
variables.
DECLARE
v_customer VARCHAR2(50) := 'Womansport';
v_credit_rating VARCHAR2(50) := 'EXCELLENT';
BEGIN
DECLARE
v_customer NUMBER(7) := 201;
v_name VARCHAR2(25) := 'Unisports';
BEGIN
v_credit_rating :='GOOD';

END;

END;

Supplement
Selecting the link title opens the resource in a new browser window.

Launch window

View this PL/SQL block of code to answer the upcoming questions.

Step 1 of 3
Identify the value and data type of the V_CUSTOMER variable in the nested block.
Options:
1.

The value is 200 and the data type is NUMBER

2.

The value is 201 and the data type is NUMBER

3.

The value is EXCELLENT and the data type is VARCHAR2

4.

The value is Womansport and the data type is VARCHAR2

Result
The value of the V_CUSTOMER variable in the nested block is 201 and its data type
is NUMBER.
Option 1 is incorrect. Although the data type of the V_CUSTOMER variable is
NUMBER, its value is 201, not 200.
Option 2 is correct. The V_CUSTOMER variable is declared with a NUMBER data
type. In the provided nested block, the value of this variable is set to 201.
Option 3 is incorrect. The variable V_CREDIT_RATING is initialized with a value of
EXCELLENT. At no point in the provided code does the variable V_CUSTOMER
have EXCELLENT as its value.
Option 4 is incorrect. The variable V_CUSTOMER is initialized with the value
Womansport in the main block. However, inside the nested block, the value of
this variable is 201.

Step 2 of 3
Identify the value and data type of the V_NAME variable in the nested block of the
provided code.
Options:
1.

The value is EXCELLENT and the data type is VARCHAR2

2.

The value is GOOD and the data type is VARCHAR2

3.

The value is Unisports and the data type is VARCHAR2

4.

The value is Womansport and the data type is VARCHAR2

Result
The value of the V_NAME variable in the nested block of the code is Unisports
and its data type is VARCHAR2.
Option 1 is incorrect. Within the nested block, the variable V_NAME is declared
with a VARCHAR2 data type and is initialized with the value Unisports. The value
EXCELLENT is the value of the V_CREDIT_RATING variable in the main block.
Option 2 is incorrect. Within the nested block, the variable V_NAME is declared
with a VARCHAR2 data type and is initialized with the value Unisports. The value
GOOD is the value of the V_CREDIT_RATING variable in the nested block.
Option 3 is correct. Within the nested block of the provided code, the variable
V_NAME is declared with a VARCHAR2 data type and is initialized with the value
Unisports.
Option 4 is incorrect. At no point in the provided code is the value of the V_NAME
variable Womansport. This is the value of the V_CUSTOMER variable in the main
block.

Step 3 of 3
Identify the value of the V_CUSTOMER variable in the main block of the provided
code.
Options:
1.

The value is 201 and the data type is NUMBER

2.

The value is 201 and the data type is VARCHAR2

3.

The value is Unisports and the data type is VARCHAR2

4.

The value is Womansport and the data type is VARCHAR2

Result
The value of the V_CUSTOMER variable in the main block of the code is
Womansport and its data type is VARCHAR2.
Option 1 is incorrect. In the nested block of the provided code, the value of the
V_CUSTOMER variable is 201 and its data type is NUMBER. However, in the main
block, its value is Womansport and its data type is VARCHAR2.

Option 2 is incorrect. In the main block of the provided code, the data type of the
V_CUSTOMER variable is VARCHAR2. However, its value is Womansport in the
main block and 201 in the nested block.
Option 3 is incorrect. The data type of the V_CUSTOMER variable is VARCHAR2, but
at no point in the provided code is the value of this variable Unisports.
Option 4 is correct. In the main block of the provided code, the value of the
V_CUSTOMER is Womansport. Its data type is VARCHAR2.

Task 3: Adding code for specific output


For the given code block, you want to add a SQL statement to the executable section of
the PL/SQL block that stores the values of a specific employee's name and salary in
variables. You also want to change the resulting output of this PL/SQL block.
DECLARE
v_today DATE:=SYSDATE;
v_tomorrow v_today%TYPE;
v_basic_percent NUMBER:=45;
v_pf_percent NUMBER:=12;
v_fname VARCHAR2(15);
v_emp_sal NUMBER(10);
BEGIN
v_tomorrow:=v_today +1;
DBMS_OUTPUT.PUT_LINE(' Hello World ');
DBMS_OUTPUT.PUT_LINE('TODAY IS : '|| v_today);
DBMS_OUTPUT.PUT_LINE('TOMORROW IS : ' || v_tomorrow);
END;

Supplement
Selecting the link title opens the resource in a new browser window.

Launch window
View this PL/SQL block of code to answer the upcoming questions.

Step 1 of 3
You want to store the values of the FIRST_NAME and SALARY columns from the
EMPLOYEES table in the V_FNAME and V_EMP_SAL variables for the employee
with the ID 110.

Which code segment should you add to the executable section of the provided
PL/SQL block?
Options:
1.

SELECT first_name, salary IN v_fname, v_emp_sal FROM employees


WHERE employee_id=110;

2.

SELECT first_name, salary INTO v_fname, v_emp_sal FROM


employees WHERE employee_id=110;

3.

SELECT first_name, salary INTO v_fname, v_emp_sal FROM


employees;

4.

SELECT fname, salary INTO v_fname, v_emp_sal FROM employees


WHERE employee_id=110;

Result
You will use the code SELECT first_name, salary INTO v_fname,
v_emp_sal FROM employees WHERE employee_id=110;.
Option 1 is incorrect. To store the first name and salary values in the V_FNAME
and V_EMP_SAL variables, the keyword INTO is required.
Option 2 is correct. This code segment will store the first name of the employee
with the ID 110 in the V_FNAME variable. It will also store the salary of the
employee with the ID 110 in the V_EMP_SAL variable.
Option 3 is incorrect. You must specify that you want to store only the first name
and salary values for the employee with ID 110. This is done by narrowing down
the returned results using a WHERE clause.
Option 4 is incorrect. The column in the EMPLOYEES table that holds the first
names of employees is called FIRST_NAME, not FNAME.

Step 2 of 3
You want to print the word Hello and then the name of the employee stored in
the V_FNAME variable, separated by a space.
Which line should you use to replace the line DBMS_OUTPUT.PUT_LINE('
Hello World ');?
Options:
1.

DBMS_OUTPUT.PUT_LINE(' Hello ' || first_name);

2.

DBMS_OUTPUT.PUT_LINE(' Hello ' || v_fname);

3.

DBMS_OUTPUT.PUT_LINE(Hello || v_fname);

4.

DBMS_OUTPUT.WRITE_LINE(' Hello ' || v_fname);

Result
You should use this line of code:
DBMS_OUTPUT.PUT_LINE(' Hello ' || v_fname);.
Option 1 is incorrect. In this case, the call to the PUT_LINE procedure of the
DBMS_OUTPUT package requires the name of the variable and not the name of the
column.
Option 2 is correct. This line of code would result in output of Hello John
because John is the employee whose ID is 110 in the EMPLOYEES table.
Option 3 is incorrect. Although this line of code would result in Hello and the
employee name stored within the V_FNAME variable being output, it would not
include spaces between Hello and the name.
Option 4 is incorrect. The DBMS_OUTPUT package does not contain a
WRITE_LINE procedure. The PUT_LINE procedure must be used instead.
You want to calculate the contribution of an employee towards the provident fund (PF).
PF is calculated as 12% of the basic salary. Basic salary is 45% of the total salary that an
employee receives. You want to use bind variables in the calculation, and only one
expression to calculate the PF. You also want to print the employee's salary and
contribution towards PF.

Step 3 of 3
Which two lines of code should you add to the executable section of the provided
PL/SQL block?
Options:
1.

DBMS_OUTPUT.PUT_LINE('YOUR CONTRIBUTION TOWARDS PF: '||


v_emp_sal*v_basic_percent/100*v_pf_percent/100);

2.

DBMS_OUTPUT.PUT_LINE('YOUR CONTRIBUTION TOWARDS PF: '||


v_emp_sal+v_basic_percent/100*v_pf_percent/100);

3.

DBMS_OUTPUT.PUT_LINE('YOUR SALARY IS : '||v_emp_sal);

4.

DBMS_OUTPUT.PUT_LINE('YOUR SALARY IS : v_emp_sal');

Result

You would use these lines of code:


DBMS_OUTPUT.PUT_LINE('YOUR CONTRIBUTION TOWARDS PF: '||
v_emp_sal*v_basic_percent/100*v_pf_percent/100);
and
DBMS_OUTPUT.PUT_LINE('YOUR SALARY IS : '||v_emp_sal);
Option 1 is correct. This line of code will determine an employee's contribution
towards PF and display it in the format YOUR CONTRIBUTION TOWARDS PF:
<contribution>.
Option 2 is incorrect. To determine an employee's contribution towards PF, the
value of the V_EMP_SAL variable should be multiplied by the value of the
V_BASIC_PERCENT value and then divided by 100. The values of these variables
should not be added together.
Option 3 is correct. This line of code would display an employee's salary in the
format YOUR SALARY IS : <salary>.
Option 4 is incorrect. This line of code would result in YOUR SALARY IS :
v_emp_sal being displayed.

Table of Contents
| Top of page |
| Learning objective |
| Exercise overview |
| Task 1: Evaluating block scoping rules |
| Task 2: Evaluating block nesting rules |
| Task 3: Adding code for specific output |
Copyright 2008 SkillSoft. All rights reserved.
SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

Anda mungkin juga menyukai