Beruflich Dokumente
Kultur Dokumente
Introduction.................................................................................................................................................3
Assigning Values to a Variable.................................................................................................................3
Cursors.....................................................................................................................................................3
SYS_REFCURSOR..................................................................................................................................4
Cursor FOR Loops................................................................................................................................4
Cursor Variables......................................................................................................................................4
Attributes.................................................................................................................................................4
Iterative Control......................................................................................................................................5
For Loop...............................................................................................................................................5
Modularity...............................................................................................................................................5
Subprograms.......................................................................................................................................5
Packages..............................................................................................................................................6
Data Abstraction......................................................................................................................................6
Object Types........................................................................................................................................6
Error Handling.........................................................................................................................................6
Data base Triggers...................................................................................................................................7
KEY Notes................................................................................................................................................7
Handling NULL Values in Comparisons and conditional Statements.......................................................8
Tiggers.........................................................................................................................................................9
Creating DML Triggers...........................................................................................................................10
Trigger Timing....................................................................................................................................10
The Triggering Event..........................................................................................................................10
Trigger type.......................................................................................................................................10
Trigger Body......................................................................................................................................11
Triggering sequence..........................................................................................................................11
Syntax for Creating DML Statement Triggers.....................................................................................11
Creating a DML Row Trigger..............................................................................................................12
Using OLD and NEW Qualifiers..........................................................................................................13
INSTEAD OF Triggers..........................................................................................................................13
Managing Triggers.............................................................................................................................14
Trigger Test Cases..............................................................................................................................14
Trigger Execution Model and Constraint Checking................................................................................14
Large Objects.............................................................................................................................................15
LONG and LOB Data types.................................................................................................................15
Components of a LOB........................................................................................................................16
Exception Handling....................................................................................................................................16
Trapping Exceptions..........................................................................................................................17
Trapping a Non predefined Oracle Server Exception.........................................................................17
Error Trapping Functions...................................................................................................................18
Trapping User Defined Exceptions.....................................................................................................18
Procedures................................................................................................................................................18
Block structure for Subprograms...........................................................................................................19
Benefits of Subprograms...................................................................................................................19
Procedure..........................................................................................................................................19
Methods for Passing Parameters.......................................................................................................20
Default Option for Parameters..........................................................................................................20
Declaring Sub programs.....................................................................................................................21
Exception Handling in Procedures.........................................................................................................21
Functions...................................................................................................................................................21
Syntax for Creating funcitons.............................................................................................................21
Advantages of User Defined functions..................................................................................................22
Procedure Or Functions.........................................................................................................................23
Benefits of Stored Procedures and Functions........................................................................................23
Managing Subprograms.............................................................................................................................23
Definer’s Rights......................................................................................................................................23
Managin Stored PL/SQL Objects............................................................................................................23
Packages....................................................................................................................................................24
Package development.......................................................................................................................24
Creating the Package specification....................................................................................................25
Advantages of Packages........................................................................................................................25
Cursors......................................................................................................................................................26
Explicit Cursor........................................................................................................................................26
Controlling Explicit cursors................................................................................................................26
Explicit Cursor Attributes.......................................................................................................................27
CURSOR FOR Loops................................................................................................................................28
Cursors with Parameters.......................................................................................................................28
Ref Cursor..................................................................................................................................................29
Composite Data Types...............................................................................................................................30
Records..................................................................................................................................................30
The %ROWTYPE Attribute......................................................................................................................30
INDEX BY Tables.....................................................................................................................................31
Using INDEX BY table Methods..............................................................................................................32
Introduction
You can use sub blocks in executable and exception handling parts of a pl/sql block but not in the
declarative part. Also, you can define local subprograms in the declarative part of any block. However,
you can call local subprograms only from the block in which they are defined.
Forward referencing of the variables is not allowed in PL/SQL, you must declare a constant or variable
before referencing it in other statements, including other declarative statements.
Declaring a constant is like declaring a variable except that you must add the keyword CONSTANT and
immediately assign a value to the constant.
Cursors
A PL/SQL construct called cursor lets you name a work area and access its stored information. There are
2 kinds of cursors:
1. Implicit
2. Explicit
PL/SQL implicitly declares a cursor for all SQL data manipulation statements, including queries that
return only one row. For queries that return more than one row, you can explicitly declare a cursor to
process the rows individually.
The set of rows returned by a multi row query is called the result set. Its size is the number of
rows that meet your search criteria.
You use OPEN, FETCH and CLOSE statements to control a cursor. The OPEN statement executes
the query associated with the cursor, identifies the result set, and positions the cursor before the first
row. The FETCH statement retrieves the current row and advances the cursor to the next row. When the
last row is processed, the CLOSE statement disables the cursor.
SYS_REFCURSOR
This is used to pass cursor from and to a stored procedure. This is a pre declared weak ref cursor.
DECLARE
CURSOR c1 IS
SELECT ename, sal, hiredate, deptno FROM emp;
...
BEGIN
FOR emp_rec IN c1 LOOP
...
salary_total := salary_total + emp_rec.sal;
END LOOP;
To reference individual fields in the record, you use dot notation, in which a dot severs as the
component selector.
Cursor Variables
Like a Cursor, a cursor variable points to the current row in the result set of a multi row query. But unlike
a cursor, a cursor variable can be opened for any type compatible query. It is not tied to a specific query.
Typically, you open a cursor variable by passing it to a stored procedure that declares a cursor variable
as one of its formal parameters.
Attributes
A % sign serves as the attribute indicator.
1. %TYPE: attribute provides the data-type of a variable or database column. Ex my_title books.title
%TYPE
a. Declaring my_title with %TYPE has 2 advantages. First, you need not know the exact
data type of title. Second, if you change the database definition of title the data-type of
my_title changes accordingly.
2. %ROWTYPE: Records are used to group data. A record consists of a number of related fields in
which data values can be stored. The %ROWTYPE attribute provides a record type that
represents a row in a table. The record can store an entire row of data selected from the table
or fetched from a cursor or cursor variable.
a. Columns in a row and corresponding fields in a record have the same names and data
types. Ex: DECLARE dept_rec dept%ROWTYPE;
Iterative Control
For Loop
FOR num IN 1..500 LOOP
END LOOP;
If the condition in the WHILE loop is false or null then the loop is bypassed and control passes to next
statement.
The EXIT WHEN statement lets you complete a loop if further processing is impossible or undesirable.
When this statement is encountered, the condition in the WHEN clause is evaluated. If the condition is
true, the loop completes and control passes to the next statement.
GOTO is also used in PL/SQL. The label is an undeclared identifier enclosed by double angle brackets.
Modularity
Modularity lets you break an application down into manageable, well defined modules. PL/SQL meets
this need with program units, which includes blocks, subprograms, and packages.
Subprograms
PL/Sql has two types of subprograms called procedures and functions, which can take parameters and be
called. A subprogram is a miniature program, beginning with a header followed by an optional
declarative part, an executable part, and an optional exception handling part.
Packages
PL/SQL lets you bundle logically related types, variables, cursors and subprograms into a package.
Packages usually have two parts: a specification and a body. The specification is the interface to your
applications; it declares the types, constants, variables, exceptions, cursors and subprograms available
for use. The body defines cursors and subprograms and so implements the specification.
Only the declarations in the package specification are visible and accessible to applications.
Implementation details are hidden and inaccessible.
Packages can be compiled and stored in an Oracle database, where their contents can be shared by
many applications. When you call a packaged subprogram for the first time, the whole package is loaded
into memory. So, subsequent calls to related subprograms in the package require no disk I/O. Thus,
packages can enhance productivity and improve performance
Data Abstraction
Object Types
In PL/SQL object oriented programming is based on object types. An object type encapsulates a data
structure along with the functions and procedures needed to manipulate the data. The variables that
form the data structure are called attributes. The functions and procedures that characterize the
behavior of the object type are called methods.
Error Handling
When an error occurs, an exception is raised. That is normal execution stops and control transfers to the
exception handling part of your PL/SQL block or subprogram. To handle raised exceptions, you write
separate routines called exception handlers.
Predefined exceptions are raised implicitly by the runtime system. You must raise user defined
exceptions explicitly with the RAISE statement.
You can define your own exceptions in the declarative part of any PL/SQL block or subprogram.
In the executable part, you check for the condition that needs special attention. If you find that
condition exists, you execute a RAISE statement.
DECLARE
...
comm_missing EXCEPTION; -- declare exception
BEGIN
...
IF commission IS NULL THEN
RAISE comm_missing; -- raise exception
END IF;
bonus := (salary * 0.10) + (commission * 0.15);
EXCEPTION
WHEN comm_missing THEN ... -- process the exception
KEY Notes
Some PL/SQL keywords are not reserved by SQL. For example, you can use the PL/SQL reserved word
TYPE in a CREATE TABLE statement to name a database column. But, if a SQL statement in your program
refers to that column, you get a compilation error. To prevent the error, enclose the uppercase column
name in double quotes (“TYPE”).
Given that single quotes delimit string literals, how do you represent an apostrophe within a string?
Here, you write two single quotes, which is not the same as writing a double quote.
You use the keyword DEFAULT instead of the assignment operator to initialize variables. For example,
the declaration
Use DEFAULT for variables that have a typical value. Use the assignment operator for variables (such as
counters and accumulators) that have no typical value.
You cannot assign nulls to a variable defined as NOT NULL. If you try, PL/SQL raises the predefined
exception VALUE_ERROR. The NOT NULL constraint must be followed by an initialization clause.
Acc_id INTEGER (4) NOT NULL := 9999;
Fields in a %ROWTYPE record do not inherit the NOT NULL column constraint
PL/SQL allows aggregate assignment between entire records if their declarations refer to the same table
or cursor. However, if one of the record’s declaration refers to a table and the other to a cursor then
aggregate assignment is not possible.
Select list items fetched from a cursor associated with %ROWTYPE must have simple names, or if they
have expressions, must have aliases.
Some languages allow you to declare a list of variables that have the same data type. PL/SQL does not
allow this. You must declare each variable separately.
Naming convention:
raise_salary(...); -- simple
emp_actions.raise_salary(...); -- qualified
raise_salary@newyork(...); -- remote
In the first case, you simply use the procedure name. In the second case, you must qualify the name
using dot notation because the procedure is stored in a package called emp_actions. In the third case,
using the remote access indicator (@), you reference the database link newyork because the procedure
is stored in a remote database. In the fourth case, you qualify the procedure name and reference a
database link.
Within the same scope, all declared variables must be unique. So, ever if their data-types differ,
variables and parameters cannot share the same name.
In the case of ambiguity, the names of database columns take precedence over the names of local
variables and formal parameters.
You can use a subprogram name to qualify references to local variables and formal parameters.
The scope of an identifier is that region of a program unit from which you can reference the identifier.
An identifier is visible only in the regions from which you can reference the identifier using an
unqualified name.
Tiggers
A trigger is a Pl/sql block or a pl/sql procedure associated with a table, view, schema, or the database.
Executes implicitly whenever a particular event takes place. Triggers can be either:
Application triggers execute implicitly whenever a particular data manipulation language (DML)
event occurs within an application. Database triggers execute implicitly when a data event such as DML
on a table, an INSTEAD OF trigger on a view, or data definition language (DDL) statements such as
CREATE and ALTER are issued, no matter which user is connected or which application is used. Database
triggers also execute implicitly when some user actions or database system actions occur, for example,
when a user logs on, or the DBA shut downs the database.
Database triggers can be system triggers on a database or a schema. With a database, triggers fire
for each event for all users; with a schema, triggers fire for each event for that specific user.
Design triggers to perform related actions, centralize global operations. Do not design triggers
where functionality is already built into the oracle server and that duplicate other triggers. Create stored
procedures and invoke them in a trigger, if the PL/SQL code is very lengthy. The excessive use of triggers
can result in complex interdependencies, which may be difficult to maintain in large applications.
Creating DML Triggers
A triggering statement contains:
1. Trigger timing: It tells when the trigger fires in relation to the triggering event.
a. For table: BEFORE, AFTER
b. For View: INSTEAD OF
2. Triggering event: INSERT, UPDATE, or DELETE
3. Table name: on table, view
4. Trigger type: Row or statement
5. When clause: restricting condition
6. Trigger body: pl/sql block
If multiple triggers are defined for a table, be aware that the order in which multiple triggers of the same
type fire is arbitrary. To ensure that triggers of the same type are fired in a particular order, consolidate
the triggers into one trigger that calls separate procedures in the desired order.
Trigger Timing
BEFORE: Execute the trigger body before the triggering DML event on a table.
AFTER: Execute the trigger body after the triggering DML event on a table.
INSTEAD OF: Execute the trigger body instead of the triggering statement. This is used for views
that are not otherwise modifiable.
Before triggers enable you to eliminate unnecessary processing of the triggering statement and its
eventual rollback in cases where an exception is raised in the triggering action. They help deriving
column values before completing a triggering INSERT or UPDATE statement. They also help in initializing
global variables or flags, and to validate complex business rules.
INSTEAD OF Trigger is used to provide a transparent way of modifying views that cannot be modified
directly through SQL DML statements because the view is not inherently modifiable. You can write
INSERT, UPDATE, and DELETE statements against the view. The INSTEAD OF trigger works invisibly in the
background performing the action coded in the trigger body directly on the underlying tables.
Trigger type
Statement: The trigger body executes once for the triggering event. This is the default. A
statement trigger fires once, even if no rows are affected at all.
Row: The trigger body executes once for each row affected by the triggering event. A row trigger
is not executed if the triggering event affects no rows.
A statement trigger is fired once on behalf of the triggering event, even if no rows are affected at all.
Statement triggers are useful if the trigger action does not depend on the data from rows that are
affected or on data provided by the triggering event itself: For example, a trigger that performs a
complex security check on the current user.
A row trigger fires each time the table is affected by the triggering event. If the triggering event affects
no rows, a row trigger is not executed.
Trigger Body
The trigger action defines what needs to be done when the triggering event is issued. This block can
contain constructs such as variables, cursors, exceptions, and so on. You can also call a pl/sql procedure
or a java procedure. The size of a trigger cannot be more than 32K.
Triggering sequence
Use the following firing sequence for a trigger on a table, when a single row is manipulated:
SQL statement does not differentiate statement triggers from row triggers, because exactly one row is
inserted into the table using this syntax.
Use the following firing sequence for a trigger on a table, when many rows are manipulated:
When the triggering data manipulation statement affects many rows, the statement trigger fires exactly
once, and the row trigger fires once for every row affected by the statement.
Timing
ON table_name
Trigger_body
Trigger name Is the name of the trigger
Timing BEFORE
AFTER
Event INSERT
UPDATE [OF column]
DELETE
Table/view_name Indicates the table associated with the trigger
Trigger body Is the trigger body that defines the action
performed by the trigger, beginning with either
DECLARE or BEGIN, ending with END, or a call to a
procedure
Trigger names must be unique with respect to other triggers in the same schema. Trigger names do not
need to be unique with respect to other schema objects, such as tables, views, and procedures.
Using column names along with the UPDATE clause in the trigger improves performance, because the
trigger fires only when that particular column is updated and thus avoids unintended firing when any
other column is updated.
When a database trigger fails, the triggering statement is automatically rolled back by the Oracle server.
You can combine several triggering events into one by taking advantage of the special conditional
predicates INSERTING, UPDATING, and DELETING within the trigger body.
Timing
ON table_name
[WHEN (condition)]
Trigger_body
In the timing field one more value is added in case of row triggers: INSTEAD OF. The conditional
predicate in WHEN must be enclosed in paranthesis and is evaluated for each row to determine whether
or not the trigger body is executed.
You can create a BEFORE row trigger in order to prevent the triggering operation from succeeding if a
certain condition is violated.
Using OLD and NEW Qualifiers
Within a ROW trigger, reference the value of a column before and after the data change by prefixing it
with the OLD and NEW qualifier.
Prefix these qualifiers with a colon (:) in every SQL and pl/sql statement. There is no colon prefix if the
qualifiers are referenced in the WHEN restricting condition.
The NEW qualifier cannot be prefixed with a colon in the WHEN clause because the WHEN clause is
outside the PL/SQL blocks.
INSTEAD OF Triggers
Use INSTEAD OF triggers to modify data in which the DML statement has been issued against an
inherently non-updatable view. These triggers are called INSTEAD OF triggers because, unlike other
triggers, the Oracle server fires the trigger instead of executing the triggering statement. This trigger is
used to perform an INSERT, UPDATE, or DELETE operation directly on the underlying tables.
A view cannot be modified by normal DML statements if the view query contains set operators,
group functions, and clauses such as GROUP BY, CONNNECT BY, START, the DISTINCT operator, or joins.
For example, if a view consists of more than one table, an insert to the view may entail an insertion into
one table and an update to another. So, you write an INSTEAD OF trigger that fires when you write an
insert against the view. Instead of original insertion, the trigger body executes, which results in an
insertion of data into one table and an update to another table.
If a view is inherently updateable and has INSTEAD OF triggers, the triggers take precedence.
INSTEAD OF triggers are row triggers. The CHECK option for views is not enforced when insertions or
updates to the view are performed by using INSTEAD OF triggers. The INSTEAD OF trigger body must
enforce the check.
Creating INSTEAD OF triggers: INSTEAD OF triggers can only be row triggers: if FOR EACH ROW is
omitted, the trigger is still defined as a row trigger.
Triggers Procedures
Defined with CREATE TRIGGER Defined with CREATE PROCEDURE
Data dictionary contains source code in Data dictionary contains source code in
USER_TRIGGERS USER_SOURCE
Implicitly invoked Explicitly invoked
COMMIT, SAVEPOINT, and ROLLBACK are not COMMIT, SAVEPOINT and ROLLBACK are allowed
allowed
Triggers are fully compiled when the CREATE TRIGGER command is issued and the code is stored in the
data dictionary. If errors occur during the compilation of a trigger, the trigger is still created.
Managing Triggers
Disable or reenable a database Trigger:
To remove a trigger from the database, use the DROP TRIGGER syntax:
When a trigger fires, the tables referenced in the trigger action may undergo changes by other users’
transactions. In all cases, a read-consistent image is guaranteed for modified values the trigger needs to
read or write.
Large Objects
LOBS are used to store large unstructured data such as text, graphic images, films, and sound
waveforms. There are four large object data types:
LOBs are characterized in two ways, according to their interpretation by the Oracle server (binary or
character) and their storage aspects. LOBs can be stored internally (inside the database) or in host files.
There are two categories of LOBs:
The oracle 9i server performs implicit conversion between CLOB and VARCHAR2 data types. The other
implicit conversions between LOBs are not possible. BFILEs can be accessed only in read only mode from
an Oracle server.
LONG and LONG RAW data types were previously used for unstructured data, such as binary images,
documents, or geographical information. These data types are superseded by the LOB data types.
LOBs store a locator in the table and the data in a different segment, unless the data is less than 4000
bytes; LONGs store all data in the same data block. In addition, LOBs allow data to be stored in a
separate segment and tablespace, or in a host file.
LOBs support random piecewise acess to the data through a file like interface; LONGs are restricted to
sequential piecewise access.
The TO_LOB function can be used to convert LONG and LONG RAW values in a column to LOB values.
You use this in the SELECT list of a subquery in an INSERT statement.
Components of a LOB
There are two distinct parts of a LOB:
1. LOB value: The data that consitutes the real object being stored.
2. LOB Locator: A pointer to the location of the LOB value stored in the database.
A LOB column does not contain the data; it contains the locator of the LOB value. When a user creates
an internal LOB, the value is stored in the LOB segment and a locator to the out-of-line LOB value is
placed in the LOB column of the corresponding row in the table. External LOBs store the data outside
the database, so only a locator to the LOB value is stored in the table.
Exception Handling
An exception is an identifier in PL/SQL that is raised during the execution of a block that terminates its
main body of actions. Exceptions can be raised in two ways:
Trapping an Exception: If the exception is raised in the executable section of the block, processing
branches to the corresponding exception handler in the exception section of the block. If PL/SQL
successfully handles the exception, then the exception does not propagate to the enclosing block or
environment. The PL/SQL block terminates successfully.
Propagating an Exception: If the exception is raised in the executable section of the block and there is
no corresponding exception handler then the PL/SQL block terminates with failure and the exception is
propagated to the calling environment.
Trapping Exceptions
EXCEPTION
Statement1;
Statement2;
Statement1;…
The exception handling section traps only those exceptions that are specified; any other exceptions are
not rapped unless you use the OTHERS exception handler. This traps any exception not yet handled. For
this reason, OTHERS is the last exception handler that is defined.
Only one exception handler is processed before leaving the block. PL/SQL declares predefined
exceptions in the STANDARD package.
When an exception is raised, normal execution of your PL/SQL block or subprogram stops and control
transfers to its exception handling part.
In PL/SQL, the PRAGMA EXCEPTION_INIT tells the complier to associate an exception name with an
oracle error number. That allows you to refer to any internal exception by name and to write a specific
handler for it.
PRAGMA (also called pseudoinstructions) is the keyword that signifies that the statement is a compiler
directive, which is not processed when the PL/SQL block is executed. Rather, it directs the compiler to
interpret all occurrences of the exception name within the block as the associated Oracle server error
number.
That means you don’t have to raise the non predefined Oracle server exception, you only need to
declare and handle it.
Code – 0 refers to No exception encountered and code – 1 refers to User defined exceptions.
Note: Use the RAISE statement by itself within an exception handler to raise the same exception back to
the calling environment.
If PL/SQL raises an exception and the current block does not have a handler for that exception, the
exception propagates in successive enclosing blocks until it finds a handler If none of these blocks
handle the exception, an unhandled exception in the host environment results.
The above procedure can be used to issue user defined error messages from stored procedures.
Error_number is a user specified number for the exception from -20000 and -20999. Message is user
specified message for the exception. It is a character string up to 2048 bytes long. If TRUE, the error is
placed on the stack of previous errors, if false, the default, the error replaces all previous errors.
RAISE_APPLICATION_ERROR can be used in either (or both) the executable section and the exception
section of a PL/SQL program. The returned error is consistent with how the Oracle server produces a
predefined, non-predefined, or user defined error.
Procedures
A subprogram is a named PL/SQL block that can accept parameters and be invoked from a calling
environment. This provides modularity, reusability, extensibility, and maintainability. A subprogram is of
two types:
A subprogram is based on standard PL/SQL structure that contains a declarative section, an executable
section, and an optional exception handling section. A subprogram can be compiled and stored in the
database.
Modularization is the process of breaking up large blocks of code into groups of code called
modules. After code is modularized, the modules can be reused by the same program or shared by other
programs. It is easier to maintain and debug code of smaller modules than a single large program. Also,
the modules can be easily extended for customization by incorporating more functionality, if required,
without affecting the remaining modules of the program.
IS | AS
Declaration Section
BEGIN
Executable Section
EXCEPTION (optional)
Exception section
END;
The executable section between the BEGIN and END keywords is mandatory, enclosing the body of
actions to be performed. There must be at least one statement existing in this section. There should be
at least a NULL; statement, that is considered an executable statement.
Benefits of Subprograms
1. Easy maintenance
2. Improved data security and integrity
3. Improved performance: Avoid reparsing for multiple users by exploiting the shared SQL area.
Avoid parsing at run time by parsing at compile time. Reduce the number of calls to the
database and decrease network traffic by bundling commands.
4. Improved code clarity
Procedure
A procedure can be compiled and stored in the database as a schema object. Syntax for creating
Procedures is:
PL/SQL Block;
PL/SQL block starts with either BEGIN or the declaration of local variables and ends with either END or
END procedure_name. modes are of 3 types:
Actual Parameters: variables or expressions referenced in the parameter list of a subprogram call.
Actual parameters are evaluated and results are assigned to formal parameters during the subprogram
call. It is good practice to use different names for formal and actual parameters. Formal parameters
have the prefix p_ in this course and actual parameters are prefixed with v_ most of the times.
To improve performance with OUT and IN OUT parameters, the compiler hint NOCOPY can be used to
request to pass by reference.
You can assign default values only to parameters of the IN mode. OUT and IN OUT parameters are not
permitted to have default values. If passed, we get a compilation error.
If an actual parameter is not passed, the default value of its corresponding formal parameter is used.
Note: all the positional parameters should precede the named parameters in a subprogram call.
Otherwise, you will receive an error message.
Declaring Sub programs
You can declare subprograms in any PL/SQL block. This is an alternative to creating the stand alone
procedures. Subprograms declared in this manner are called local subprograms. Because they are
defined within a declaration section of another program, the scope of local subprograms is limited to the
parent block in which they are defined.
Note: You must declare the subprogram in the declaration section of the block, and it must be the last
item, after all the other program items. For example, a variable declared after the end of the
subprogram, before the BEGIN of the procedure, will cause a compilation error.
However, when an exception is raised in a called procedure, control immediately goes to the exception
section of that block. If the exception is unhandled, the block terminates, and control goes to the
exception section of the calling procedure. If the exception is handled in the calling procedure, all DML
statements in the calling procedure and in the called procedure remain as part of the transaction, they
are not rolled back.
If the exception is unhandled in the calling procedure, the calling procedure terminates and the
exception propagates to the calling environment. All the DML statements in the calling procedure and
the called procedure are rolled back along with any changes to any host variables.
Functions
A function is a named PL/SQL block that returns a value. A function must return a value to the calling
environment, whereas a procedure returns zero or more values to its calling environment. A function
must have a RETURN clause in the header and at least one RETURN statement in the executable section.
A function stored in the database is referred to as a stored function. Functions promote reusability and
maintainability.
IS/AS
PL/SQL Block;
The RETURN data type must not include a size specification. Only IN parameters should be declared in
functions.
The PL/SQL compiler generates the pseudo-code or P code, based on the parsed code. The PL/SQL
engine executes this when the procedure is invoked. Use SHOW ERRORS to see compilation errors.
Note: if there are any compilation errors and you make subsequent changes to the CREATE FUNCTION
statement, you either have to drop the function first or use the OR REPLACE syntax.
To be callable from SQL expressions, a user defined function must meet certain requirements.
1. Parameters to a PL/SQL function called from a SQL statement must use positional notation.
Named notation is not supported.
2. Accept only IN parameters.
3. Stored functions cannot be called from the CHECK constraint clause of a CREATE or ALTER TABLE
command or be used to specify a default value for a column.
4. You must own or have the EXECUTE privilege on the function to call it from a SQL statement.
5. The function must return data types that are valid SQL data types. They cannot be pl/sql specific
data types such as BOOLEAN. The same restriction applies to parameters of the function.
6. Only stored functions are callable from SQL statements. Stored procedures cannot be called.
7. Functions that are callable from SQL expressions cannot contain OUT and IN OUT parameters.
Other functions can contain parameters with these modes, but it is not recommended.
8. Functions called from SQL expressions cannot contain DML expressions.
All the privileges granted on a function are revoked when the function is dropped. The CREATE OR
REPLACE syntax is equivalent to dropping a function and recreating it. Privileges granted on the function
remain the same when this syntax is used.
Managing Subprograms
Privileges that use the word CREATE or ANY are system privileges; for example, GRANT ALTER ANY
TABLE TO green;
Object privileges are rights assigned to a specific object within a schema and always include the name of
the object. For example, scott can assign privileges to Green to alter his EMPLOYEES table as follows:
Simply DBA grants System privileges and Owner grants Object privileges.
To create a subprogram, you must have the system privilege CREATE PROCEDURE. You can alter, drop,
or execute subprograms without any further privileges being required.
If a subprogram refers to any objects that are not in the same schema, you must be granted access to
these explicitly, not through a role.
If the ANY keyword is used, you can create, alter, drop, or execute your own subprograms and those in
another schema. Note that ANY keyword is optional only for the CREATE PROCEDURE privilege. For the
remaining ALTER ANY PROCEDURE, DROP ANY PROCEDURE, EXECUTE ANY PROCEDURE it is not.
Definer’s Rights
By default the subprogram executes under the security domain of the owner. This is referred to as
definer’s rights.
To ensure that the procedure executes using the security of the executing user, and not the owner, use
AUTHID CURRENT_USER (after writing the header before IS). This ensures that the procedure executes
with the privileges and schema context of its current user.
Packages
Packages bundle related PL/SQL types, items, and subprograms into one container. A package usually
has a specification and a body, stored separately in the database. The specification is the interface to
your applications. It declares all types, variables, constants, exceptions, cursors, and subprograms
available for use. The package specification may also include PRAGMAs, which are directives to the
compiler.
The package itself cannot be called, parameterized, or nested. When you call a packaged PL/SQL
construct for the first time, the whole package is loaded into the memory. Thus, later calls to constructs
in the same package require no disk input/output.
Package development
You create a package in two parts: first the package specification, and then the package body. Public
package constructs are those that are declared in the package specification and defined in the package
body. Private package constructs are those that are defined solely within the package body.
A package specification can exist without a package body, but a package body cannot exist without a
package specification.
Creating the Package specification
CREATE [OR REPLACE] PACKAGE package_name
IS/AS
Subprogram specifications
END package_name;
Variables declared in the package specification are initialized to NULL by default. All the constructs
declared in a package specification are visible to users who are granted privileges on the package.
The public procedures or functions are routines that can be invoked repeatedly by other constructs in
the same package or from outside the package.
IS/AS
Subprogram bodies
END package_name;
The order in which subprograms are defined within the package body is important: you must declare a
variable before another variable or subprogram can refer to it, and you must declare or define private
subprogram before calling them from other subprograms.
Advantages of Packages
1. Modularity: encapsulate related constructs.
2. Hiding information: only the declarations in the package specification are visible and accessible
to applications.
a. Private constructs in the package body are hidden and inaccessible.
b. All coding is also hidden in the body.
3. Added functionality: packaged public variables and cursors persist for the duration of a session.
Thus, they can be shared by all subprograms that execute in the environment. They also enable
you to maintain data across transactions without having to store it in the database. Private
constructs also persist for the duration of the session, but can only be accessed within the
package.
4. Better performance: The entire package is loaded into memory when the package is first
referenced. There is only one copy in memory for all users. The dependency hierarchy is
simplified.
5. Overloading: multiple subprograms of the same name, which means you can create multiple
subprograms with the same name in the same package, each taking parameters of different
number of datatype.
Cursors
The Oracle server uses work areas, called private SQL areas, to execute SQL statements and to store
processing information. You can use PL/SQL cursors to name a private SQL area and access its stored
information.
PL/SQL allows you to refer to the most recent implicit cursor as the SQL cursor.
Explicit Cursor
Use explicit cursors to individually process each row returned by a multiple row SELECT statement. The
set of rows returned by a multiple row query is called the active set. Its size is the number of rows that
meet your search criteria. The Cursor marks the current position in the active set.
1. Dynamically allocates memory for a context area that eventually contains crucial processing
information.
2. Parses the SELECT statement
3. Binds the input variables – sets the value for the input variables by obtaining their memory
addresses.
4. Identifies the active set. Rows in the active set are not retrieved into variables when the OPEN
statement is executed. Rather, the FETCH statement retrieves the rows.
5. Positions the pointer just before the first row in the active set.
Note: If the query returns no rows when the cursor is opened, PL/SQL does not raise an exception.
1. Reads the data for the current row into the output PL/SQL variables.
2. Advances the pointer to the next row in the identified set.
The CLOSE statement disables the cursor, and the active set becomes undefined. The CLOSE statement
releases the context area.
Before the first fetch, %NOTFOUND evaluates to NULL. So, if FETCH never executes successfully, the
loop is never exited. Therefore, to be safe, use the following EXIT statement instead:
When the cursor or cursor variable is opened, %ROWCOUNT is zeroed. Before the first fetch,
%ROWCOUTN yields 0. Thereafter, it yields the number of rows fetched so far.
CURSOR FOR Loops
FOR record_name IN cursor_nameLOOP
Statement1;
Statement2;
END LOOP;
Here, implicit open, fetch, exit and close occur. The record is implicitly declared. Supply the parameters
for a cursor, if required, in parentheses following the cursor name in the FOR statement.
When you use a sub query in a FOR loop, you do not need to declare a cursor.
CURSOR cursor_name
[(parameter_name datatype,…)]
IS
Select_statement;
Pass parameter values to a cursor when the cursor is opened and the query is executed. Open an explicit
cursor several times with a different active set each time.
You can pass parameters to the cursor in a cursor FOR loop. This means that you can open and close an
explicit cursor several times in a block, returning a different active set on each occasion. For each
execution, the previous cursor is closed and re opened with a new set of parameters.
Each formal parameter in the cursor declaration must have a corresponding actual parameter in the
OPEN statement. Parameter data types are the same as those for scalar variables, but you do not give
them sizes. The parameter names are for references in the query expression of the cursor.
When the cursor is opened, you pass values to each of the parameters by position or by name.
Note: the parameter notation does not offer greater functionality; it simply allows you to specify input
values easily and clearly. This is particularly useful when the same cursor is referenced repeatedly.
DECLARE
BEGIN
CLOSE emp_cursor;
CLOSE emp_cursor;
END;
Ref Cursor
A ref cursor is basically a data type. A variable created based on such a data type is generally called a
cursor variable. A cursor variable can be associated with different queries at run time. The primary
advantage of using cursor variables is their capability to pass result sets between sub programs (like
stored procedures, functions, packages etc.).
There are two basic types: Strong ref cursor and weak ref cursor. For strong ref cursor the returning
columns with data types and length need to be known at the compile time. For weak ref cursor the
structure does not need to known at the compile time.
Since Oracle 9i you can use SYS_REFCURSOR as the type for the returning REF_CURSOR.
Composite Data Types
Like scalar variables, composite variables have a data type. Composite data types (also known as
collections) are RECORD, TABLE, NESTED TABLES, and VARRAY.
You use the RECORD data type to treat related but dissimilar data as a logical unit. You use the
TABLE data type to reference and manipulate collections of data as a whole object.
Records
Records must contain one or more components of any scalar, record, or index by table data type, called
fields. Records are not the same as rows in a database table. Treat a collection of fields as a logical unit.
Syntax:
(field_declaration [, field_declaration]…);
Identifier type_name;
The field_type is the data type of the field. It represents any PL/SQL data type except REF CURSOR. The
NOT NULL constraint prevents assigning nulls to those fields. Be sure to initialize NOT NULL fields.
Field declarations are like variable declarations. There are no predefined data types for PL/SQL records,
as there are for scalar variables. Therefore you must create the record type first and then declare an
identifier using that type.
INDEX BY Tables
Objects of the TABLE type are called INDEX BY tables. They are modeled as (but not the same as)
database tables. INDEX BY tables use a primary key to provide you with array like access to rows.
An INDEX BY Table :
1. Is similar to an array
2. Must contain two components:
a. A primary key of data type BINARY_INTEGER that indexes the INDEX BY table
b. A column of scalar or record data type, which stores the INDEX BY table elements.
3. Can increase dynamically because it is unconstrained.
Syntax:
[INDEX BY BINARY_INTEGER];
Identifier type_name;
INDEX BY BINARY_INTEGER;
Ename_table ename_table_type;
The NOT NULL constraint prevents nulls from being assigned to the PL/SQL table of that type. Do not
initialize the INDEX BY table.
INDEX BY tables can have one column and a unique identifier to that one column, neither of which can
be named. The column can belong to any scalar or record data type, but the primary key must belong to
the BINARY_INTEGER. You cannot initialize an INDEX BY table in its declaration. An INDEX BY table is not
populated at the time of declaration. It contains no keys or no values. An explicit executable statement
is required to initialize the INDEX BY table.
The magnitude range of a BINARY_INTEGER is -2147483647 … 2147483647, so the primary key value can
be negative. Indexing does not need to start with 1.
Note: The table.EXISTS(i) statement returns TRUE if a row with index I is returned. Use the EXISTS
statement to prevent an error that is raised in reference to a non-existing table element.
Using INDEX BY table Methods
A INDEX BY table method is a built in procedure or function that operates on tables and is called using
dot notation.
Method Description
EXISTS (n) Returns TRUE if the nth element in a PL/SQL table
exists
COUNT Returns the number of elements that a PL/SQL
table currently contains
FIRST and LAST Returns the first and last (smallest and largest)
index numbers in a PL/SQL table. Returns NULL if
the PL/SQL table is empty.
PRIOR (n) Returns the index number that preceeds index n in
a PL/SQL table
NEXT(n) Returns the index number that succeeds index n in
a PL/SQL table
TRIM TRIMM removes one element from the end of a
PL/SQL table. TRIM(n) removes n elements from
the end of a PL/SQL table.
DELETE DELETE removes all elements from a PL/SQL table.
DELETE(n) removes the nth element from a PL/SQL
table.
DELETE(m, n) removes all elements in the range m
… n from a PL/SQL table.
Sequences
A sequence is an object in Oracle that is used to generate a number sequence. This can be useful when
you need to create a unique number to act as a primary key.
MINVALUE value
MAXVALUE value
INCREMENT BY value
CACHE value;
To retrieve the next value in the sequence order, you need to use nextval. Ex: sequence_name.nextval
With respect to sequence, the cache option specifies how many sequence values will be stored in
memory for faster access. The downside of creating a sequence with cache is that if a system failure
occurs, all cached sequence values that have not been used, will be “lost”. This results in a gap in the
assigned sequence values. When the system comes back up, Oracle will cache new numbers from where
it left off in the sequence, ignoring the so called “lost” sequence values.
To recover the lost sequence values, you can always execute an ALTER SEQUENCE command to
reset the counter to the correct value.
Nocache means that none of the sequence values are stored in the memory. This option may sacrifice
some performance; however, you should not encounter a gap in the assigned sequence values.
The START WITH clause is optional and specifies the rows that are the roots of the hierarchical query. If
you omit this clause, then Oracle uses all rows in the table as root rows. The START WITH condition can
contain a subquery, but it cannot contain a scalar subquery expression.
The CONNECT BY clause specifies the relationship between parent rows and child rows of the hierarchy.
The connect by condition can be any condition, however, it must use the PRIOR operator to refer to the
parent row. The connect by condition cannot contain a regular or scalar subquery expression.
Sys_connect_by_path it returns the path of a column value from root to node, with column values
separated by char for each row returned by CONNECT BY condition.
CONNECT BY specifies the relationship between the parent rows and the child rows of the hierarchy.
One expression in condition must be qualified with the PRIOR operator to refer to the parent row. If the
CONNECT BY condition is compound, then only one condition requires the PRIOR operator, although you
can have multiple PRIOR conditions.
Materialized View
A materialized view is a database object that contains the results of a query. They are local copies of
data located remotely, or are used to create summary tables based on aggregations of a table’s data.
Materialized views, which store data based on remote tables, are also known as snapshots.
Materialized view is a concept used in Data warehousing. These views contain the data itself.
However, views do not have data themselves but point to the data. We can make DML statements on
materialized views. Materialized are summary tables to faster the retrieval of data so that joins will
minimize so that the performance increases. Materialized view is physical duplicate data in a table, view
is logical representation of table.
A view is a virtual table representing the results of a database query. Whenever an ordinary view’s table
is queried or updated, the DBMS converts these into queries or updates against the underlying base
tables.
A materialized view takes a different approach in which the query result is cached as a concrete
table that may be updated from the original base tables from time to time. This enables much more
efficient access, at the cost of some data being potentially out of date. It is most useful in data
warehousing scenarios, where frequent queries of the actual base tables can be extremely expensive.
Indexes can be built on any column of the materialized view, enabling drastic speed ups in query
time. In a normal view, it’s typically only possible to exploit indexes on columns that come directly from
(or have mapping to) indexed columns in the base tables.
Without the use of views the normalization of database above second normal form would
become much more difficult. ORDER BY clause in the view definition is meaningless.
If the database system can determine the reverse mapping from the view schema to the schema
of the underlying base tables, then the view is updatable.
1. Load the data into temporary tables via SQL * Loader via control file and make the data native to
ORACLE.
2. Write a PL/SQL program to do the processing.
3. Load the data into live tables.
This approach has a lot of dependencies as well as strong lack of integration of steps and programmatic
control. UTL_FILE package is used to overcome these problems. With some creative use of this package
we can achieve whatever SQL * Loader offers and in addition to that do some high level validation and
complex data loading.
Brief Overview of SQL * Loader
This is a server utility for loading data from external data files into Oracle database. The basic advantage
of using SQL * Loader is for simple loads and fast loading of data. It can load data into myriad data
formats, perform elementary filtering, load data into multiple tables, and create one logical record from
one or more physical records.
It creates a detailed log file, a bad file that contains rejected records and a discard file to hold
the records that are selectively not loaded. The tool is executed from command line and a username and
password and the control file name and location are required to run it.
The security mechanism for UTL_FILE is achieved by defining a parameter in INIT.ora file called
url_file_dir parameter.
Conclution
If the data load is complex UTL_FILE seems to be the tool of choice.