2019-Cpe-27 DBMS Lab Manual 12
2019-Cpe-27 DBMS Lab Manual 12
Submitted To:
Engr. M Ubaidullah
Submitted By:
Muhammad Usama Saghar
Roll Number:
2019-CPE-27
Subject:
THEORY
BEGIN – mandatory o
SQL statements o
PL/SQL statements
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.
▪
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;
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
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.
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.
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.
*****