You are on page 1of 13

Meghnad Saha Institute of Technology

PL/SQL Lesson 1.1


Please do not expect any further study material

Sourabh Maity
2/14/2011
Contents
1 Overview ………………………………………………................................................ 3
1.1 About PL/SQL …………………………………………………………………... 3
1.2 PL/SQL environment ……………………………………………………………. 3
1.3 PL/SQL benefit ………………………………………………………………….. 5
2 Blocks and variables …………………………………………………………………. 7
2.1 PL/SQL block structure …………………………………………………………. 7
2.2 Block types ……………………………………………………………………… 8
2.3 Handling variables ………………………………………………………………. 8
2.4 Types of variables ……………………………………………………………….. 8
2.5 Declaring variables ……………………………………………………………… 9
2.6 Scalar data type …………………………………………………………………. 10
2.7 The %TYPE attribute …………………………………………………………… 11
3 Input and output …………………………………………………………………….. 12
3.1 Output something ……………………………………………………………….. 12
3.2 Taking input ……………………………………………………………………... 13

2
Chapter 1

Overview
In this chapter you are introduced to the features and benefits of PL/SQL.

1.1 About PL/SQL


Procedural Language/SQL (PL/SQL) is Oracle Corporation’s procedural language extension to
SQL, the standard data access language for relational databases. PL/SQL offers modern software
engineering features such as data encapsulation, exception handling, information hiding, and brings
state-of-the-art programming to the Oracle Server and toolset.

PL/SQL incorporates data manipulation and query statements of SQL to be included in block-
structured and procedural units of code, making PL/SQL a powerful transaction processing
language. With PL/SQL, you can use SQL statements to finesse Oracle data, and PL/SQL control
statements to process the data.

1.2 PL/SQL Environment


PL/SQL is not an Oracle product in its own right; it is a technology used by the Oracle server
and by certain Oracle tools. Blocks of PL/SQL are passed and processed by a PL/SQL engine, which
may reside within the tool or within the Oracle server. The engine that is used depends on where the
PL/SQL block is invoked from.

SQL, SQL*Plus, PL/SQL: What's the Difference?

This question has bedeviled many people new to Oracle. There are several products with the
letters "SQL" in the title, and these three, SQL*Plus, SQL, and PL/SQL, are often used together.
Because of this, it's easy to become confused as to which product is doing the work and where the
work is being done. This section briefly describes each of these three products.

SQL

SQL stands for Structured Query Language. This has become the lingua franca (A medium of
communication between peoples of different languages) of database access languages. It has been
adopted by the International Standards Organization (ISO) and has also been adopted by the
American National Standards Institute (ANSI). When you code statements such as
SELECT, INSERT, UPDATE, and DELETE, SQL is the language you are using. It is a declarative

3
language and is always executed on the database server. Often you will find yourself coding SQL
statements in a development tool, such as PowerBuilder or Visual Basic, but at runtime those
statements are sent to the server for execution.

PL/SQL

PL/SQL is Oracle's Procedural Language extension to SQL. It, too, usually runs on the database
server, but some Oracle products such as Developer/2000 also contain a PL/SQL engine that resides
on the client. Thus, you can run your PL/SQL code on either the client or the server depending on
which is more appropriate for the task at hand. Unlike SQL, PL/SQL is procedural, not declarative.
This means that your code specifies exactly how things get done. As in SQL, however, you need
some way to send your PL/SQL code up to the server for execution. PL/SQL also enables you to
embed SQL statements within its procedural code. This tight-knit relationship between PL/SQL,
SQL, and SQL*Plus is the cause for some of the confusion between the products.

SQL*Plus

SQL*Plus is an interactive program that allows you to type in and execute SQL statements. It
also enables you to type in PL/SQL code and send it to the server to be executed. SQL*Plus is one of
the most common front ends used to
develop and create stored PL/SQL
procedures and functions.

What happens when you run SQL*Plus


and type in a SQL statement? Where does
the processing take place? What exactly
does SQL*Plus do and what does the
database do? If you are in a Windows
environment and you have a database
server somewhere on the network, the
Figure 1.1: Relationship between SQL, PL/SQL and SQL *Plus
following things happen:

1. SQL*Plus transmits your SQL query over the network to the database server.

2. SQL*Plus waits for a reply from the database server.

3. The database server executes the query and transmits the results back to SQL*Plus.

4. SQL*Plus displays the query results on your computer screen.

Even if you're not running in a networked Windows environment, the same things happen. The
only difference might be that the database server and SQL*Plus are running on the same physical
machine. This would be true, for example, if you were running Personal Oracle on a single PC.

PL/SQL is executed in much the same manner. Type a PL/SQL block into SQL*Plus, and it is
transmitted to the database server for execution. If there are any SQL statements in the PL/SQL

4
code, they are sent to the server's SQL engine for execution, and the results are returned back to the
PL/SQL program.

The important thing is that SQL*Plus does not execute your SQL queries. SQL*Plus also does
not execute your PL/SQL code. SQL*Plus simply serves as your window into the Oracle database,
which is where the real action takes place. Figure 1.1 illustrates this relationship.

1.3 Benefits of PL/SQL


PL/SQL plays a central role in both the Oracle server (through stored procedures, stored
functions, database triggers, and packages) and Oracle development tools. In this section of the
chapter we explore some other beneficial features of PL/SQL.

Improved performance

PL/SQL can improve the performance of an application. It can be used to group SQL statements
together within a single block and to send the entire block to the server in a single call, thereby
reducing the network traffic.
SQL
If…Then
SQL
Else Oracle with
Application
SQL PL/SQL
End if;
SQL

Figure 2: Communication between apps and Oracle.

PL/SQL block structure

Every unit of PL/SQL comprises of one or more blocks. These blocks can be entirely separate or
nested one with another. The basic units (procedures, functions) that make up a PL/SQL program are
logical blocks, which can contain any number of nested sub blocks. Therefore one can exploit every
advantage of modularized program development.

Portability

Because PL/SQL is native to Oracle server, you can move programs to any host environment
(OS or platform) that supports Oracle server and PL/SQL.

Identifiers

In PL/SQL you can use identifiers to do the following:

- Declare variables, cursors, constants, and exceptions and then use them in SQL and
procedural statements.
- Declare variables dynamically based on data structure of tables and columns in the database.

5
Procedural language control structure

Procedural language control structures allow you to do the following:

- Execute a sequence of statements conditionally.


- Execute a sequence of statements iteratively in a loop.
- Process individually the rows returned by a multiple-row query with an explicit cursor.

Errors

The error handling functionality in PL/SQL allows you to do the following:

- Process Oracle server errors with exception-handling routines.


- Declare user-defined error conditions and process them with exception-handling routines.

Benefits of subprograms

Stored procedures and functions have many benefits in addition to modularizing application
development:

- Easy maintenance.
- Improved data security and integrity by doing the following:
~ Control indirect access to database objects from non-privileged users.
~ Ensure that related actions are performed together; or not at all.
- Improved code clarity.

6
Chapter 2

Blocks and variables


In this chapter we now dig into some more depth in writing PL/SQL program.

2.1 PL/SQL block structure


We know that PL/SQL is a block structured language. A PL/SQL block consists of up to three
sections. The following table summarizes the things up.

Sections Description Inclusion


Declarative Contains all variables, constants, cursors and user Optional
defined exceptions that are referenced in the
executable and declarative section.
Executable Contains SQL statements to manipulate data in the Mandatory
database and PL/SQQL statements to manipulate the
data in block.
Exception handling Specifies the actions to perform when error and Optional
abnormal conditions arise in the executable section.
Table 1.1: Sections of PL/SQL block.

An example skeleton of a PL/SQL block is given below:

DECLARE (Optional)

Variables, cursors, user-defined exceptions

BEGIN (Mandatory)

- SQL statements
- PL/SQL statements

EXCEPTION (Optional)

Actions to perform when error occurs

END; (Mandatory)

Now just check out some basic syntax of writing PL/SQL programs.

- Place a semicolon (;) at the end of a SQL statement or PL/SQL statement.


7
- When the block is executed successfully, without unhandled exception or compile-time
errors, the message output should be as follows:
PL/SQL procedure successfully completed.
- Section keywords DECLARE, BEGIN and EXCEPTION are not followed by semicolons.
- END and all other PL/SQL statements require a semicolon to terminate the statement.
- You can string statements together on the same line, but this is not advised for clarity of
editing.

2.2 Block Types


Now we discuss about the basic units (procedures and functions, also known as subprograms,
and anonymous blocks).

Anonymous blocks

Anonymous blocks are unnamed blocks. They are declared at the point in an application where
they are to be executed and are passed to the PL/SQL engine for execution at run time.

Subprograms

Subprograms are named PL/SQL blocks that can accept parameters and can be invoked. You can
declare them either as procedures or as functions. Generally we use a procedure to perform an action
and a function to compute a value.

2.3 Handling variables


Declare and initialize variables in the declaration section

You can declare variables in the declarative part of any PL/SQL block and subprogram.
Declaration allocates storage space for a value, specify its data type, and name the storage location
so that you can reference it. Forward references are not allowed. You must declare a variable before
referencing it in other statements.

Pass values into PL/SQL subprograms through parameters

There are three parameter modes, IN (the default), OUT, and IN OUT. Use the IN parameter to
pass values to the subprograms being called. Use OUT parameter to return values to the caller of a
subprogram. And use the IN OUT parameter to pass the initial values to the subprogram being
called and return updated values to the caller.

2.4 Types of variables


All PL/SQL variables have a data type, which specifies a storage format, constraints, and valid
range of values. PL/SQL supports four data type categories--- scalar, composite, reference and LOB
(large object). The last two will not possibly be covered in the entire course.

8
- Scalar data types hold a single value. The main data types are those that correspond to
column types in Oracle server tables; PL/SQL also supports Boolean variables.
- Composite data types, such as records, allow groups of fields to be defined and manipulated
in PL/SQL blocks.
- Reference data types hold values, called a pointer that designates other program items.
- LOB data types hold values, called locators that specify the location of large objects (such as
graphic images) that are stored out of line.

2.5 Declaring variables


You must declare all PL/SQL identifiers in the declaration section before referencing them in the
PL/SQL block. You have the option to assign an initial value to a variable. If you refer to other
variables in a declaration, you must be sure to declare them separately in a previous statement.

Syntax:

identifier [CONSTANT] data type [NOT NULL] [ = | DEFAULT expr ];

In the syntax:

identifier is the name of the variable.

CONSTANT constrains the variable so that its value cannot be changed; constants
must be initialized.

data type is a scalar, composite, reference, or LOB data type.

NOT NULL constrains the variable so that it must contain a value; NOT NULL
variables must be initialized.

expr can be a literal expression, another variable, or an expression involving


operators and functions.
DEFAULT Use this keyword instead of assignment operator ( =) to initialize
variables.
So, you have come enough to have the first example PL/SQL program.

Example 1:

Compute the bonus @10% of basic salary of the employee having id 007 from the employees
table.

DECLARE

v_bonus NUMBER(8,2);

v_bonus_percentage NUMBER(3,2) DEFAULT 0.1;

BEGIN

9
SELECT salary * v_bonus

INTO v_bonus

FROM employees

WHERE employee_id = 007;

END;

Note the slash (/) at the end. It has nothing to do with PL/SQL; it signifies to the SQL *Plus editor
the end of PL/SQL program.

2.6 Scalar data 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 sub types that associate a base type to a constraint. For example, INTEGER and
POSITIVE are sub types of the NUMBER base type.

Data Type Description


CHAR [(max_length)] Base type for fixed length character data up to 32,767 bytes.
Default length (if max_length is not specified) is set to 1.
VARCHAR2(max_length) Base type for variable length character data up to 32,767 bytes.
No default length for VARCHAR2 variables and constants.
LONG Base type for variable length character data up to 32,760 bytes.
NUMBER[(precision, scale)] Precision can range from 1 to 38, and scale can range from -84 to
127.
BOOLEAN Base type that stores one of the three possible values used for
logical calculations: TRUE, FALSE, or NULL.
DATE Base data types for dates and time. DATE values include the time
of the day in seconds since midnight. The range for dates is
between 4712 B.C. to 9999 A.D.
INTERVAL YEAR TO Use this data type to store and manipulate intervals of years and
MONTH months. The syntax is: INTERVAL YEAR [(precision)] TO
MONTH where precision specifies the number of digits in the
year field. You must use an integer literal in the range 0…4 in the
precision field. The default is 2.
INTERVAL DAY TO Use this data type to store and manipulate intervals of days,
SECOND hours, minutes, and second. The syntax 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
must use an integer literal in the range 0…9 in the precision field.
The default is 2 and 6 respectively.
10
Examples:

v_job VARCHAR2(9);
v_total_sal NUMBER(9,2) = 0;
v_order_date DATE = SYSDATE + 7;
c_tax_rate CONSTANT NUMBER (3,2) = 12.50;
v_valid BOOLEAN NOT NULL = TRUE;

2.7 The %TYPE attributes


When you declare PL/SQL variables to hold column value, you must ensure that the variables
are of the correct data type and precision. If it is not PL/SQL error will occur during execution.

Rather than hard coding the data type and precision of a variable, you can use %TYPE attribute
to declare a variable according to another previously declared variable or database column.

Syntax:

identifier Table.column_name%TYPE;

Example:

v_name employees.name%TYPE;
v_min_balance v_balance%TYPE = 10;

A NOT NULL database column attribute doesn’t 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 it.

11
Chapter 3

Input and output


In this section we will learn how to interact with the users, i.e. how to take input from and give
output to the users through PL/SQL.

3.1 Output something


The DBMS_OUTPUT package was introduced in Oracle7. DBMS_OUTPUT is used to allow
output to the buffer in SQL*Plus from PL/SQL blocks. The PL/SQL DBMS_OUTPUT package has
a PUT_LINE procedure to allow you to write data to flat file or to direct your PL/SQL output to a
screen.

In order to use the DBMS_OUTPUT package for printing, you must issue the following
command in SQL*Plus.

SET SERVEROUTPUT ON

The messages can be easily kept disabled by using DBMS_OUTPUT.DISABLE. Any


PUT_LINE messages are silently ignored if you have DISABLEd DBMS_OUTPUT (or failed to
ENABLE).

Actually, SQL*Plus's SET SERVEROUTPUT ON will call DBMS_OUTPUT.ENABLE.

Example:

scott > BEGIN


2 DBMS_OUTPUT.DISABLE;
3 DBMS_OUTPUT.PUT_LINE('Disabled');
4 DBMS_OUTPUT.ENABLE;
5 DBMS_OUTPUT.PUT_LINE('Enabled');
6 END;
7/

Output:

Enabled

PL/SQL procedure successfully completed.


12
3.2 Taking input
You have two SQL*Plus command to serve the purpose. One is PROMPT and the other is
ACCEPT. PROMPT is used to prompt the user and ACCEPT is used to receive response from the
user.

Example:

SET SERVEROUTPUT ON

PROMPT Enter two nos

ACCEPT a

ACCEPT b

DECLARE

X NUMBER;

Y NUMBER;

Z NUMBER;

BEGIN

X = &a;

Y = &b;

Z = X + Y;

DBMS_OUTPUT.PUT_LINE (‘Sum =’ || Z); -- Note ‘||’, it is the concatenation operator.

END;

13

You might also like