0% found this document useful (0 votes)
73 views

2019-Cpe-27 DBMS Lab Manual 12

The document discusses the basic features of PL/SQL programming, including PL/SQL block structure which consists of a declarative, executable, and exception handling section; different types of PL/SQL blocks such as anonymous blocks, stored procedures and functions, triggers, and packages; variables in PL/SQL including scalar, composite, reference, and LOB variables; and how to declare PL/SQL variables by specifying the identifier, data type, optional constraints, and initial value.

Uploaded by

Haalim M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

2019-Cpe-27 DBMS Lab Manual 12

The document discusses the basic features of PL/SQL programming, including PL/SQL block structure which consists of a declarative, executable, and exception handling section; different types of PL/SQL blocks such as anonymous blocks, stored procedures and functions, triggers, and packages; variables in PL/SQL including scalar, composite, reference, and LOB variables; and how to declare PL/SQL variables by specifying the identifier, data type, optional constraints, and initial value.

Uploaded by

Haalim M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lab Manual # 12

Submitted To:
Engr. M Ubaidullah
Submitted By:
Muhammad Usama Saghar

Roll Number:
2019-CPE-27
Subject:

Database Management Systems (CPE-221)

Department of Computer Engineering


UCE&T
Bahauddin Zakariya University, Multan.
Lab Session 12
OBJECTIVE
Basic features of PL/SQL Programming

THEORY

P rocedural Language/SQL (PL/SQL) is Oracle Corporation’s procedural language extension to SQL,


the standard data access language for relational databases. It allows the 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.

PL/SQL offers modern software engineering features such as data encapsulation,


exception handling, information hiding, and OBJECT orientation, and so brings state-of-the-art
programming to the Oracle Server and Toolset.
PL/SQL BLOCK STRUCTURE
A PL/SQL block consists of up to three sections: declarative (optional), executable
(required), and exception handling (optional). Only BEGIN and END keywords are required. The
following illustrates the PL/SQL block structure:-
DECLARE - Optional o Variables, cursors,
userdefined exceptions

BEGIN – mandatory o
SQL statements o
PL/SQL statements

EXCEPTION – optional o Actions to perform


when errors occur
END; - Mandatory

Table 12.1
BLOCK TYPES
Every unit of PL/SQL comprises one or more blocks. These blocks can be entirely separate
or nested one within another. The basic units (procedures and functions, also known as
subprograms, and anonymous blocks) that make up a PL/SQL program are logical blocks, which
can contain any number of nested sub-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 runtime. You can
embed an anonymous block within a precompile program and within SQL*Plus or Server Manager.
Triggers in Oracle Developer components consist of such blocks.
Subprograms
Subprograms are named PL/SQL blocks that can take parameters and can be invoked. We
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.
We can store subprograms at the server or application level. Using Oracle Developer
components (Forms, Reports and Graphics), we can declare procedures and functions as part of
the application (a Form or report) and call them from other procedures, functions and triggers
within the same application whenever necessary.
Note: A function is similar to a procedure, except that a function must return a value.

PROGRAM CONSTRUCTS
The following table outlines a variety of different PL/SQL program constructs that use the
basic PL/SQL block. They are available based on the environment in which they are executed.
Program Description Availability
Construct
Anonymous Unnamed PL/SQL block that is embedded All PL/SQL
block within an application or is issued interactively environments
Stored Named PL/SQL block stored in the Oracle Oracle Server
procedure or Server that can accept parameters and can be
function invoked repeatedly by name.
Application Named PL/SQL block stored in an Oracle Oracle Developer
procedure or Developer application or shared library that can components – for
function accept parameters and can be invoked example, forms
repeatedly by name
Package Named PL/SQL module that groups related Oracle Server and Oracle
procedures, functions and identifiers Developer components –
for example, Forms
Database PL/SQL block that is associated with a database Oracle Server
trigger table and is fired automatically when triggered
by DML statements
Application PL/SQL block that is associated with an Oracle Developer
trigger application event and is fired automatically components – for
example, Forms
Table 12.2
VARIABLES IN PL/SQL
With PL/SQL we can declare variables and then use them in SQL and procedural statements
anywhere an expression can be used. Uses of Variables
Following are various uses of variables:-
Temporary storage of data
Data can be temporarily stored in one or more variables for use when validating data input
for processing later in the data flow process.

Manipulation of stored values
Variables can be used for calculations and other data manipulations without accessing the
database.

Reusability
Once declared, variables can be used repeatedly in an application simply be referencing them
in other statements, including other declarative statements.
▪ Ease of maintenance

When using %TYPE and %ROWTYPE, we declare variables basing the declarations on the
definitions of database columns. PL/SQL variables or cursor variables previously declared in the
current scope may also use the %TYPE and %ROWTYPE attributes as datatype specifiers. If an
underlying definition changes, the variable declaration changes accordingly at runtime. This
provides data independence, reduces maintenance costs, and allows programs to adapt as the
database changes to meet new business needs.
The variables can be handled in the following manner:-

Declare and initialize variables in the declaration section.

Assign new values to variables in the executable section.

Pass values into PL/SQL subprograms through parameters. There are three parameter modes,
IN (default), OUT and IN OUT. The IN parameter is used to pass values to the subprogram
being called, the OUT parameter is used to return values to the caller of a subprogram and the
IN OUT parameter is used to pass initial values to the subprogram being called and to return
updated values to the caller.

View the results from a PL/SQL block through output variables.
Types of Variables
All PL/SQL variables have a datatype, which specifies a storage format, constraints and valid
range of values. PL/SQL supports four datatype categories – scalar, composite, reference, and
LOB (large OBJECT) – that can be used to declare variables, constants and pointers.
• PL/SQL variables
o Scalar:
Holds a single value and has no internal components.
The main datatypes are those that correspond to column types in Oracle Server tables;
PL/SQL also supports Boolean variables. Scalar data types can be classified into four
categories: number, character, date and Boolean. Character and number datatypes have
subtypes that associate a base type to a constraint. For example, INTEGER and POSITIVE
are subtypes of the NUMBER base type.
o Composite:
For example, records that allows groups of fields to be defined and manipulated in
PL/SQL blocks.
o Reference:
Holds values, called pointers that designate other program
items. o LOB (large OBJECTs):
Holds values, called locators that specify the location of large OBJECTs (graphic
images for example) that are stored out of line.
o Non-PL/SQL variables:
Host language variables declared in precompile programs. Screen fields in Forms
applications o SQL*Plus host variables: PL/SQL does not have input/output capability of
its own. In order to pass values into and out of a PL/SQL block, it is necessary to rely on the
environment in which PL/SQL is executing is executing. SQL*Plus host (or bind) variables
can be used to pass runtime values out of the PL/SQL block back to the SQL*Plus
environment. You can reference them in a PL/SQL block with a preceding column.

Declaring PL/SQL variables


It is necessary to declare all PL/SQL identifiers in the declaration section before referencing
them in the PL/SQL block. It is optional to assign an initial value. It is not necessary to assign a
value to a variable in order to declare it.
Syntax
identifier [CONSTANT] datatype [NOT NULL] [:= |
DEFAULT expr];
Examples:
Declare
v_hiredate DATE;
v_deptno NUMBER(2) NOT NULL := 10;
v_location VARCHAR2(13) := ‘Atlanta’;
c_comm. CONSTANT NUMBER := 1400;
v_count BINARY_INTEGER := 0;
v_orderdate DATE:= SYSDATE + 7;
Guidelines:

Name the identifier according to the same rules used for SQL OBJECTs.

Use naming conventions – for example, v_name to represent a variable, g_name to represent global
variables and c_name to represent a constant variable.

If NOT NULL constraint is used, it is needed to assign a value.

Declaring only one identifier per line makes code more easily read and maintained.
Identifiers must not be longer than 30 characters. The first character must be a letter; the
remaining characters can be letters, numbers, or special symbols.
Assigning values to variables
Syntax
identifier := expr;
Examples
Set a predefined hiredate for new employees
v_hiredate := ’31-DEC-98’;
Set the employee name to ‘Maduro’
v_ename := ‘Maduro’;
Another way to assign values to variables is to select or fetch database values into it. The
following example, computes a 10% bonus on the salary of an employee:-

SELECT SAL * 0.10


INTO V_BONUS
FROM EMP
WHERE EMPNO = 7369;
Then we can use the variable bonus in another computation or insert its value into a database
table.
Variable Initialization and Keywords
Variables are initialized every time a block or subprogram is entered. By default, variables are
initialized to NULL.

Use the assignment operator (:=) for variables that have no typical value.
V_hiredate := to_date(’15-SEP-1999’, ‘DD-MON-YYYY’);

DEFAULT. We can use the DEFAULT keyword instead of the assignment operator to initialize
variables. Use the default for variables that have a typical value.


NOT NULL. Impose the NOT NULL constraint when the variable must contain a value.
We cannot assign nulls to a variable defined as NOT NULL. The NOT NULL constraint
must be followed by an initialization clause.
v_location VARCHAR2(13) NOT NULL := ‘CHICAGO’;
Scalar Datatypes
A scalar datatype holds a single value and has no internal components. Scalar datatypes can
be classified into four categories: number, character, date, and Boolean. Character and number
datatypes have subtypes that associate a base type to a constraint. For example, INTEGER and
POSITIVE are subtypes of the NUMBER base type.
Basic Scalar Datatypes
Datatype Description
VARCHAR2(maximum Base type for variable-length character data up to 32,767 bytes.
length) There is no default size for VARCHAR2 variables and constants.
NUMBER Base type for fixed and floating-point numbers.
[(precision, scale)]
DATE 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 9999 A.D.
CHAR Base type for fixed-length character data upto 32, 760 bytes. If
[(maximum length)] the maximum length is not specified, the default length is set to 1.
LONG Base type for variable-length character data up to 32,760 bytes.
The maximum width of a LONG database column is
2,147,483,647 bytes.
LONG RAW Base type for binary data and byte strings up to 32,760 bytes.
LONG RAW data is not interpreted by PL/SQL.
BOOLEAN Base type that stores one of three possible values used for logical
calculations TRUE, FALSE, or NULL.
BINARY_INTEGER Base type for integers between –2,147,483,647 and
2,147,483,647.
PLS_INTEGER 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 and BINARY_INTEGER values.
Table 12.3
Note:
The LONG datatype is similar to VARCHAR2, except that the maximum length of a LONG
value is 32,760 bytes.
Scalar Variable Declarations
Following are some examples of variable declarations in PL/SQL.
v_job VARCHAR2(9); v_count
BINARY_INTEGER := 0; v_total_sal
NUMBER(9, 2) := 0; v_orderdate DATE :=
SYSDATE + 7; c_tax_rate CONSTANT
NUMBER(5,2) := 8.25; v_valid BOOLEAN
NOT NULL := TRUE;
The %TYPE Attribute
When we declare PL/SQL variables to hold column values, it is necessary to ensure that the
variable is of the correct datatype and precision. Rather than hard coding the datatype and
precision of a variable, we 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 will be derived from a table in the database or if the variable is
destined to be written to.
To use the attribute in place of the datatype required in the variable declaration, prefix it with
the database table and column name. If referring to a previously declared variable, prefix the
variable name to the attribute.
Examples
v_ename emp.ename%TYPE;
v_balance NUMBER(7,2);
v_min_balance v_balance%TYPE := 10;

Declaring Boolean Variables


Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable. In PL/SQL,
we can compare variables in both SQL and procedural statements. In a SQL statement, we 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 missing,
inapplicable or unknown value. For example, to declare and initialize a Boolean variable:-
v_comm._sal BOOLEAN := (v_sal1 < v_sal2);
Composite Datatypes
Composite datatypes (also known as collections) are TABLE, RECORD, NESTED TABLE,
and VARRAY. We use the RECORD datatype to treat related but dissimilar data as a logical unit.
The TABLE data type is used to reference and manipulate collections of data as a whole OBJECT.
The composite data types are not covered in this workbook.
LOB Datatype Variables
With the LOB (Large OBJECT) Oracle 8 data types, we can store blocks of unstructured data
(such as text, graphic images, video clips, and sound wave forms) up to 4 gigabytes in size. LOB
data types allow efficient, random, piecewise access to the data and can be attributes of an
OBJECT type. LOBs also support random access to data.

The CLOB (character large OBJECT) datatype is used to store large blocks of singlebyte character
data in the database.

The BLOB (binary large OBJECT) datatype is used to store large binary OBJECTs in the database
in line (inside the row) or out of line (outside the row).

The BFILE (binary file) datatype is used to store large binary OBJECTs in operating system files
outside the database.

The NCLOB (national language character large OBJECT) datatype is used to store large blocks of
single-byte or fixed-width multi-byte NCHAR data in the database, in line or out
of line.
Bind Variables
A bind variable is a variable that is declared in the host environment and then used to pass
runtime values, either number or character, into or out of one or more PL/SQL programs, which
can use it as they would use any other variable. Variables declared in the host or calling
environment can be referenced in PL/SQL statements, unless the statement is in a procedure,
function or package. This includes host language variables declared in pre-compiler programs,
screen fields in Oracle Developer Forms applications, and SQL*Plus bind variables.
Creating Bind Variables
To declare a bind variable in the SQL*Plus environment, we use the command
VARIABLE. For example, to declare a variable of type NUMBER and VARCHAR2 as follow:-
VARIABLE return code NUMBER
VARIABLE returns VARCHAR2 (30);
Displaying Bind Variables
To display the current value of bind variables in the SQL*Plus environment, we use the
command PRINT. The following example illustrates a PRINT command.
VARIABLE g_n NUMBER
PRINT g_n
Referencing Non-PL/SQL variables
To reference host variables, prefix the references with a colon ( : ) to distinguish them from
declared PL/SQL variables. The following example computes the monthly salary based upon the
monthly annual salary supplied by the user. This script contains both SQL*Plus commands as well
as a complete PL/SQL block.
VARIABLE g_monthly_salary NUMBER
ACCEPT p_annual_sal PROMPT ‘Please enter the annual salary : ‘

DECLARE
v_sal NUMBER(9, 2) := &p_annual_sal;
BEGIN
:g_monthly_sal := v_sal / 12;
END;
/
PRINT g_monthly_sal
Table 12.4
DBMS_OUTPUT.PUT_LINE
DBMS_OUTPUT is an Oracle-supplied package, and PUT_LINE is a procedure within that
package. PUT_LINE procedure is used to display information from a PL/SQL block. The package
must first be enabled on SQL*Plus session. To do this, execute the SQL*Plus command SET
SERVEROUTPUT ON.
Example
The following script computes the monthly salary and prints it to the screen, using
DBMS_OUTPUT.PUT_LINE.
SET SERVEROUTPUT ON
ACCEPT p_annual_sal PROMPT ‘Please enter the annual salary : ‘

DECLARE
v_sal NUMBER(9, 2) := &p_annual_sal; BEGIN
v_sal := v_sal / 12;
DBMS_OUTPUT.PUT_LINE (‘The monthly salary is ‘ || TO_CHAR(v_sal));
END;
/
PRINT g_monthly_sal
EXERCISES

1. Write down the different features of PL/SQL programming


language. Ans.
PL/SQL includes procedural language elements such as conditions and loops. It allows
declaration of constants and variables, procedures and functions, types and variables of those
types, and triggers. It can handle exceptions (run-time errors). Arrays are supported involving the
use of PL/SQL collections.
Features of PL/SQL
• PL/SQL is tightly integrated with SQL.
• It offers extensive error checking.
• It offers numerous data types.
2. Describe the different block types in PL/SQL
Ans.
A PL/SQL block consists of three sections: declaration, executable, and exception-
handling sections. In a block, the executable section is mandatory while the declaration and
exception-handling sections are optional. However, PL/SQL anonymous blocks can be useful for
testing purposes. In PL/SQL, that’s blocks which is not have header are known as anonymous
blocks. These blocks do not form the body of a function or triggers or procedure.
3. What are stored procedures and functions? How are they different from anonymous
blocks?
Ans.

Functions Procedures
A function does not allow output A procedure allows both input and
parameters output parameters.
You cannot manage transactions You can manage transactions inside a
inside a function. function.
Unlike the other two types of PL/SQL blocks (the procedure and the function), the
anonymous block has no name associated with it. In fact, the anonymous block is missing the header
section altogether. Instead it simply uses the DECLARE reserved word to mark the beginning of its
optional declaration section.

4. What are the different types of variables in PL/SQL? Define each of


them Ans.

Every constant, variable, and parameter have a datatype (or type), which specifies a
storage format, constraints, and valid range of values. PL/SQL provides many predefined
datatypes. For instance, you can choose from integer, floating point, character, Boolean, date,
collection, reference, and large object (LOB) types.
BINARY_INTEGER:

You use the BINARY_INTEGER datatype to store signed integers. Its magnitude range
is -2**31 .. 2**31.

BINARY_FLOAT and BINARY_DOUBLE:

Single-precision and double-precision IEEE 754-format single-precision floating-point


numbers. These types are used primarily for high-speed scientific computation.

CHAR:

You use the CHAR datatype to store fixed-length character data. How the data is
represented internally depends on the database character set.

5. What are the different numeric data types in PL/SQL? Describe each of them along
with their range of values.
Ans.
The different data types are given below:
• DEC(38)
• DECIMAL(38)
• DOUBLE PRECISION(18)
• FLOAT(18)
• INTEGER(38)
• INT
• NUMERIC(38)
• REAL
• SMALLINT(38)
6. What are bind variables? How are they created? What are their advantages/uses?
Ans.

Bind variables are placeholders for actual values in SQL statements. Writing SQL
statements with bind variables rather than substitution variables or literals minimizes processing
time and can improve application performance by 20 to 30 percent. Using bind variables can also
help prevent an SQL injection attack.

Bind variables are variables you create in SQL*Plus and then reference in PL/SQL. If
you create a bind variable in SQL*Plus, you can use the variable as you would a declared
variable in your PL/SQL subprogram and then access the variable from SQL*Plus.

The advantage of using bind variables is due to the fact that a database does not need to
rebuild its execution plan for every SQL statement. Bind variables work for SQL statements that
are exactly the same, where the only difference is in the value.

*****

You might also like