PLSQL Print
PLSQL Print
Plsql
EXECUTE IMMEDIATE is faster than DBMS_SQL
Plsql blocks:
Plsql blocks are two types
Anonymous block: The block contains any name that is
anonymous block. We cannot call in another programs. But
named blocks can be calls in anonymous blocks.
2
Plsql
Named block: This block contains named PL/SQL programs which
are stored physically in the database as schema objects.
Plsql structure:
Declaration: This is an optional section which is used for
declaration of local variables, cursors, and local subprograms. The
DECLARE keyword indicates the beginning of the declaration
section.
Execution: This is the mandatory section of a PL/SQL block which
contains the executable statements. These statements are parsed
by the PL/SQL engine and executed on the block. The BEGIN and
END keywords
indicate the beginning and end of an executable section.
Exception: This is the optional section of the block which contains
the exception handlers. The EXCEPTION keyword indicates the
start of the exception section.
What are the Plsql variables?
Plsql variables can be used for temporary storage, reusablility,
easy of maintenance.
The scope of a variable is the portion of the program in which the
variable can be accessed, or where the
Variable is visible. It usually extends from the moment of
declaration until the end of the block in which
the variable was declared.
What are the different types of datatypes available in
plsql?
Scalar: Holds a single value and does not contain any internal
components. Ex: timestamp, varchar2,char,
Number,Long,Int,Integer
Plsql
Composite: Contains the internal datatypes. Which can be
manuplated individually. It is known as collection. Ex.: TABLE,
RECORD, NESTED TABLE..
Reference: Holds the values called pointers, which designates to
the other objects. Ex: REF CURSOR, REF object_datatype.
Lob: Holds the values, which specifies the location of large
objects, such as images and vedios clips. It can stored 4GB of
unstrucrted data. Ex: BLOB,CLOB, BFILE NCLOB.
Can a variable be assigned a value from database? If yes,
then how?
Yes, a variable can be assigned a value from a database. You can
fetch the value from the database and assign it to the variable
using the into keyword, as shown in the following code:
select emp_sal * 0.20 into var_increment from t_employee where
emp_no = emp_id.
Does a NOT NULL constraint of a database column apply to
%TYPE variables?
No, a NOT NULL constraint does not apply to variables declared
using the %TYPE attribute. These variables can be assigned a null
value in a PL/SQL block, as shown in the following code snippet:
DECLARE
var_emp_code t_employee.emp_code%TYPE;
.....
BEGIN
var_emp_code := NULL;
Plsql
Can SQL group functions be used within the procedural
statements?
The SQL group functions, such as AVG, MIN, MAX, COUNT, SUM,
STDDEV, and VARIANCE, cannot be directly used within PL/SQL.
However, they can be embedded within SQL statements and then
can be utilized in the procedural statements.
Plsql
GOTO statement helps to shifting the control from one block of
code to some other block of code within plsql.
Case statement syntax:
CASE SELECTOR
WHEN EXP1 THEN STATMENT1;
Plsql
Decode:
Where decode is function. We cannot use relational operators. It
cannot be used in subqueries. It cannot be used in plsql block. It
compare the null values.
CONTINUE Statement:
Similar to the EXIT statement, the CONTINUE statement controls
loop iteration. Whereas the EXIT statement causes a loop to
terminate and passes control of the execution outside the loop,
the CONTINUE statement causes a loop to terminate its current
iteration and passes control to the next iteration of the loop
Describe the use of %ROWTYPE and %TYPE in PL/SQL
Ans: %ROWTYPE allows you to associate a variable with an entire
table row. The %TYPE associates a variable with a single column
type.
Difference between NO DATA FOUND and %NOTFOUND?
NO DATA FOUND is an exception raised only for the SELECT....INTO
statements when the where clause of the querydoes not match
any rows. When the where clause of the explicit cursor does not
match any rows the %NOTFOUND attribute is set to TRUE instead.
Plsql
CURSORS
What Is Cursor?Types Of Cursor? And Diff B/W Cursors?
Ans: The Oracle Engine uses a work area for its internal
processing in order to execute an SQL statement. This work area
is private to SQL operation and is called Cursor .Through the
cursor plsql program can control the context area.
Types of Cursor:
Implicit Cursor: Any given PL/SQL block issues an implicit cursor
when ever a SQL statement is executed, as long as an explicit
cursor does not exist for that SQL statement. The implicit cursor is
used to process INSERT, UPDATE, DELETE, and SELECT INTO
statements. During the processing of an implicit cursor, Oracle
automatically performs the OPEN, FETCH, and CLOSE operations.
Explicit Cursor: The only means of generating an explicit cursor is
to name the cursor in the DECLARE section of the PL/SQL block.
The advantage of declaring an explicit cursor over an indirect
implicit cursor is that the explicit cursor gives the programmer
more programmatic control. Also, implicit cursors are less efficient
than explicit cursors, so it is harder to trap data errors.
The process of working with an explicit cursor consists of the
following steps:
8
Plsql
1. Declaring the cursor. This initializes the cursor into memory.
2. Opening the cursor. The declared cursor is opened, and
memory is allotted.
3. Fetching the cursor. The declared and opened cursor can now
retrieve data.
4. Closing the cursor. The declared, opened, and fetched cursor
must be closed to release the memory allocation Attributes Of a
Implicit Cursor:
%ISOPEN returns TRUE if cursor is open else FALSE. Syntax is
SQL%ISOPEN
%ROWCOUNT--- returns number of records fetched from cursor. if
the cursor has not been opened, a reference to the %ROW
COUNT raises the INVALID CURSOR exception.
syntax is SQL
%ROWCOUNT
%FOUND---- returns TRUE if record is fetched successfully else
FALSE, syntax is SQL%FOUND.
%NOTFOUND-- returns TRUE if record is not fetched successfully
else FALSE syntax is SQL%NOTFOUND
Q.State the advantage and disadvantage of Cursor?
Advantage :
In pl/sql if you want perform some actions more than one records
you should user these cursors only. bye using these cursors you
process the query records. you can easily move the records and
you can exit from procedure when you required by using cursor
attributes.
disadvantage:
using implicit/explicit cursors are depended by sutiation. if the
result set is less than 50 or 100 records it is better to go for
implicit cursors. if the result set is large then you should use
exlicit cursors. other wise it will put burdon on cpu
Plsql
10
Plsql
3. Fetching the cursor. The declared and opened cursor can now
retrieve data.
4. Closing the cursor. The declared, opened, and fetched cursor
must be closed to
release the memory allocation
What is Ref Cursor?
Ans: 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 runtime. The primary advantage of using cursor variables is their
capability to pass result sets between stored procedures.
There are the two types of cursor variables
STRONG: A REF cursor is declared with RETURN type is called.
WEAK : A REF cursor is declared with out RETURN type is called.
Plsql
INLINE CURSOR:
The for loop allows defining an inline cursor. An inline cursosr is a
cursor that is not declared in the DECLARE section but the cursor
definition is included in the FOR loop.
PARAMATERIZED CURSOR:
A cursor can be declared with parameters. This enables a cursor
to generate a specific result set
that is narrow but also reusable.
. Cursor parameters make the cursor more reusable.
. Cursor parameters can be assigned default values.
. The scope of the cursor parameters is local to the cursor.
CURSOR FOR LOOP:
The cursor FOR loop specifies a sequence of statements to be
repeated once for each row returned by the cursor. Use the cursor
FOR loop if you need to FETCH and PROCESS every record from a
cursor until you want to stop processing and exit the loop.
What is FOR UPDATE clause?
The cursor FOR UPDATE clause is used only with a cursor when
you want to update tables in the database. Generally, when you
execute a SELECT statement, we are not locking any rows. The
purpose of using the FOR UPDATE clause is to lock the rows of the
tables we want to update so that another user cannot perform an
update until we perform our update and release the lock. The next
COMMIT or ROLLBACK statement releases the lock.
Using the FOR UPDATE clause locks these rows that have been
identified in the active set.
If the FOR UPDATE clause is used, rows may not be fetched from
the cursor until a COMMIT has been issued.
12
Plsql
Plsql
you can exit from procedure when you required by using cursor
attributes.
Disadvantage:
using implicit/explicit cursors are depended by sutiation. if the
result set is les than 50 or 100 records it is better to go for implicit
cursors. if the result set is large then you should use exlicit
cursors. other wise it will put burdon on cpu
What is difference between a Cursor declared in a
procedure and Cursor declared in a package
specification ?
A cursor declared in a package specification is global and can be
accessed by other procedures or procedures in a package. A
cursor declared in a procedure is local to the procedure that can
not be accessed by other procedures.
14
Plsql
TRIGGERS
What is the triggers? Types of triggers?
A database trigger is a named PL/SQL block stored in a database
and executed implicitly when a triggering event occurs. The act of
executing a trigger is called firing the trigger.
DML statements executed against a database table. Such a
trigger can fire before or after a triggering event.
A DDL statement executed either by a particular user against a
schema or by any user.
A system event such as startup or shutdown of the database.
Compound triggers These triggers act as both statement- and
row-level triggers when we insert, update, or delete data from a
table.
15
Plsql
1.statement level trigger is executed once per the DML operation,
irrespective of number of records affected by DML operation.
2.it is used when a triggering statement affects rows in a table
but the processing required is completely independent of the
number of rows affected.
What are the uses of triggers?
Enforcing complex business rules that cannot be defined by using
integrity constraints. It Preventing invalid transactions.
What are the Advantages of Triggers?
1) Triggers can be used as an alternative method for
implementing referential integrity constraints
2) By using triggers, business rules and transactions are easy to
store in database
3) It controls on which updates are allowed in a database.
4) When a change happens in a database a trigger can adjust
the change to the entire database.
5) Triggers are used for calling stored procedures.
What are the Disadvantages of Triggers?
1.Triggers can executed every time some fields in database is
updated.
2. Decrease in performance of the database: By the complex
nature of the database programs take more time to execute and
there can be hidden performance downtimes.
What is the difference b/w Triggers and Integrity
constraints?
16
Plsql
INTEGRITY CONSTRAINTS
TRIGGERS
Plsql
What is the syntax of trigger:
CREATE [OR REPLACE] TRIGGER Ttrigger_name
{BEFORE|AFTER} Triggering_event ON table_name
[FOR EACH ROW]
[FOLLOWS another_trigger] [ENABLE/DISABLE]
[WHEN condition]
DECLARE
declaration statements
BEGIN
executable statements
EXCEPTION
exception-handling statements
END;.
What are the restrictions on triggers when trigger
created?
we need to know about several restrictions before creating a
trigger:
A trigger may not issue a transactional control statement such as
COMMIT, SAVEPOINT, or ROLLBACK. When the trigger fires, all
operations performed become part of a transaction.
When this transaction is committed or rolled back, the operations
performed by the trigger are committed or rolled back as well. An
exception to this rule is a trigger that contains an autonomous
transaction.
Any function or procedure called by a trigger may not issue a
transactional control statement unless it contains an autonomous
transaction.
It is not permissible to declare LONG or LONG RAW variables in
the body of a trigger.
Row-level triggers cannot use a :new or :old pseudo-record, or row
of data, when the column is declared as a LONG or LONG RAW
datatype.
18
Plsql
FOR EACH ROW:
The clause FOR EACH ROW specifies that a trigger is a row trigger
and fires once for each row that is inserted, updated, or deleted.
What is Autonomous transaction ? Where do we use it?
Ans: An autonomous transaction is an independent transaction
that is initiated by another transaction. It must contain at least
one SQL statement.
Autonomous transactions allow a single transaction to be
subdivided into multiple commit/rollback transactions, each of
which will be tracked for auditing purposes.
When an autonomous transaction is called, the original
transaction (calling transaction) is temporarily suspended. The
autonomous transaction must commit or roll back before it
returns control to the calling transaction.
Once changes have been made by an autonomous transaction,
those changes are visible to other transact --tions in the
database. Autonomous transactions can be nested. That is, an
autonomous transaction can operate as a calling transaction,
initializing other autonomous transactions within itself.
What are Transactional Triggers ? Give the uses of
Transactional Trigger ?
Ans: Transactional Triggers fire in response to transaction
processing events. These events represent points during
application processing at which Oracle Forms needs to interact
with the data source. Examples of such events include updating
records, rolling back to save points, and committing transactions.
What is the difference b/w statement level trigger and row
level trigger?
19
Plsql
A trigger if specified FOR EACH ROW; it is fired for each of the
table being affected by the triggering statement. For example if a
trigger needs to be fired when rows of a table are deleted, it will
be fired as many times the rows are deleted.
If FOR EACH ROW is not specified, it is application to a statement
and the trigger is executed at a statement level.
Row-level: - They get fired once for each row in a table affected
by the statements.
Statement: - They get fired once for each triggering statement.
Row Level Trigger Row Level Trigger is fired each time row is
affected by Insert, Update or Delete command. If statement
doesnt affect any row, no trigger action happens.
Statement Level Trigger
This kind of trigger fires when a SQL statement affects the rows of
the table. The trigger activates and performs its activity
irrespective of number of rows affected due to SQL statement.
20
Plsql
PL/SQL provides a special kind of trigger that can be defined on
database views. This trigger is called an INSTEAD OF trigger and
is created as a row trigger.
An INSTEAD OF trigger fires instead of the triggering statement
(INSERT, UPDATE, DELETE) that has been
issued against a view and directly modifies the underlying tables.
What is :old and :new in triggers?
There are two pseudo-records when you use the FOR EACH ROW
clause in a row-level trigger.
They both refer to the columns referenced in the DML statement.
The pseudo-records are composite
variables; new or old are the pseudo-record variable names in the
WHEN clause, and :new and :old
are the bind variables in the trigger body. They differ because the
trigger declaration and body are
separate PL/SQL blocks. The new and old pseudo-records are
declared in scope by the row-level trigger declaration.
The trigger declaration is the calling block, and the trigger body is
the called block. Bind variables are passed by reference between
PL/SQL blocks when an event fires a trigger in a database session.
The elements of the pseudo-record are pseudo-fields.
The new or old pseudo-records are session-level composite
variables. Theyre implicitly declared in the scope of the triggering
event, which is the DML statement.
15.What is FOLLOWS clause triggers?
Suppose you have multiple trigger on the same event on the
same table, for instance when you have a packaged application
where you are not allowed to change any of the code. But you
want to add your own code.
If you add a trigger to an event that already has a trigger on it,
there is no way of knowing when this is executed, before or after
the existing trigger. If you rely on values that may be changed in
21
Plsql
the first trigger there was no way to be sure this trigger had been
fired before your code is executed.
Syntax:
CREATE [ OR REPLACE ] TRIGGER [schema.] trigger
{ simple_dml_trigger
| compound_dml_trigger
| non_dml_trigger
}
[ FOLLOWS [schema.] trigger [[schema.] trigger]...]
[ ENABLE | DISABLE ]
[ WHEN (condition) ]
trigger_body
if you have two (or more) triggers that follow a single trigger. One
table with three triggers in place. Trigger 2 follows trigger 1 and
trigger 3 follows trigger 1 too. Which one gets fired first? lowest
physical number will be fired first.
What is the mutating table and mutating error?( ORA-04091)
Mutating error normally occurs when we are performing some
DML operations and we are trying to select the affected record
from the same trigger. So basically we are trying to select records
in the trigger from the table that owns the trigger. This creates
inconsistency and Oracle throws a mutating error.
Mutation will not occur if a single record is inserted in the table
(using VALUES clause). If bulk insertion is done or data is inserted
from another table mutation will occur.
we can use different ways to handle mutating table errors.
22
Plsql
create statement level trigger instead of row level. If we omit the
for each row clause from above trigger, it will become statement
level trigger.
triggering statement on the table, cannot query the same table
so that trigger cannot see inconsistent data. This restriction
applies to all the row level triggers and hence we run into
mutating table error.
By defining row level trigger as an autonomous transaction, we
can solve mutating table error but result is not correct. The latest
updates are not getting reflected in our result set as oppose to
statement level trigger. So one has to be very careful when using
this approach.
In version 11g, Oracle made it much easier with introduction of
compound triggers.Let us see in this case how a compound
trigger can resolve mutating table error.
Plsql
(b) before each row change from the firing statement;
(c) after each row change from the firing statement;
(d) after the firing statement.
Compound triggers dont
support filtering actions with the WHEN clause or the use of the
autonomous transaction PRAGMA.
3. Two popular reasons to use compound trigger are:
1.
Plsql
END AFTER EACH ROW;
--Executed after DML statement
AFTER STATEMENT IS
BEGIN
NULL;
END AFTER STATEMENT;
END compound_trigger_name;
Q. Which trigger is more efficient : AFTER or BEFORE ?
A.AFTER row triggers are slightly more efficient than BEFORE row
triggers. With BEFORE row triggers, affected data blocks must be
read (logical read, not physical read) once for the trigger and then
again for the triggering statement. Alternatively, with AFTER row
triggers, the data blocks need only be read once for both the
triggering statement and the trigger.
25
Plsql
2.Triggers Restriction:
A trigger constraint specific a boolean expression
that must be TRUE for the trigger to fire. A trigger restriction is
specified using a WHEN clause.
3.Trigger Action:
The trigger action is a pl/sql block that contains the
code specification to be executed when the trigger fires. The
pl/sql code block can hold sql and plsql statements , can define
pl/sql language constructs and call stored procedures.
Can a view be mutating ?if yes, then how?
NO, view cannot be mutating like a table. If an UPDAE
statement fires an INSTEAD OF triggers on a view, the view is not
considered to be mutating. If the UPDATE statement had been
executing on a table, the table would have been considered as
mutating.
What are schema-level triggers/DDL triggers ?
Schema-level triggers are created on schemalevel operations, such as create table, alter table, drop table,
rename, and revoke. These triggers prevent DDL statements,
provide security and monitor the DDL operations.
What is cascading trigger?
When a statement in a trigger body causes another
trigger to be fired, the triggers are said to be cascading. Max = 32
26
Plsql
The table columns are referred as OLD.column_name and
NEW.column_name. For triggers related to INSERT only
NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name
NEW.column_name values only available.
For triggers related to DELETE only OLD.column_name values only
available.
What is the DML ERROR log table?
By default, all rows in a single transaction either succeed or fail. If
you insert a large volume of rows in a single insert as select, an
error in one row will force the whole insert to fail.
You can override this behavior via the use of an error log table,
along with special syntax within your commands to tell the
database how to process the errors. Oracle will then automatically
log the entries that failed and the reasons why each row failed
while the transaction itself will succeed.
In a sense this is a multitable insertthe rows that can be
inserted are added to the targeted table whereas the rows that
fail are inserted into the error log table.
27
Plsql
EXCEPTION HANDLING
1.Pre-defined exceptions:
NO_DATA_FOUND (ORA-01403) When a SELECTINTO clause
does not return any row from a table.
TOO_MANY_ROWS (ORA-01422) When you SELECT or fetch
more than one row into a record or variable.
ZERO_DIVIDE (ORA-01476) When you attempt to divide a
number by zero.
CURSOR_ALREADY_OPEN (ORA-06511) You tried to open a
cursor that is already open.
28
Plsql
INVALID_CURSOR (ORA-01001) Illegal cursor operation
occurred. You tried to reference a cursor that does not yet exist.
This may have happened because youve executed a FETCH
cursor or CLOSE cursor before Opening the cursor.
INVALID_NUMBER (ORA-01722) You tried to execute an SQL
statement that tried to convert a string to a number, but it was
unsuccessful.
DUP_VAL_ON_INDEX (ORA-00001) Attempted to insert a
duplicate value.
LOGIN_DENIED (ORA-01017) You tried to log into Oracle with an
invalid username/password combination.
NOT_LOGGED_ON (ORA-01012) You tried to execute a call to
Oracle before logging in.
VALUE_ERROR (ORA-06502) You tried to perform an operation
and there was an error on a conversion, truncation, or invalid
constraining of numeric or character data.
2.Non-predefined/unnamed exceptions
Those system exception for which oracle does not provide a name
is known as unnamed system exception. These exceptions do not
occur frequently. These Exceptions have a code and an associated
message.
There are two ways to handle unnamed system exceptions:
1. By using the WHEN OTHERS exception handler,
2. By associating the exception code to a name and using it as a
named exception.
We can assign a name to unnamed system exceptions using a
Pragma called EXCEPTION_INIT.EXCEPTION_INIT will associate a
29
Plsql
predefined Oracle error number to a programmer defined
exception name.
Pragma exception_init(err msg, err number);
Plsql
values of the code or message, you can decide which subsequent
action to take based on the error.
SQLCODE: Returns the numeric value for the error code.
SQLERRM: Returns the message associated with the error
number.
They can be used in exception handling to report or store in error
log table.
These are useful for WHEN OTHERS clause.
You cannot use SQLCODE or SQLERRM directly in a SQL
statement. Instead, you must assign their values to local
variables, then use the variables in the SQL statement, as shown
in the following example:
Plsql
RAISE_APPLICATION_ERROR is used for the following reasons,
a) to create a unique id for an user-defined exception.
b) to make the user-defined exception look like an Oracle error.
The General Syntax to use this procedure is:
RAISE_APPLICATION_ERROR (error_number, error_message);
Plsql
WHEN exception_name1 THEN
[statements]
WHEN exception_name2 THEN
[statements]
WHEN exception_name_n THEN
[statements]
WHEN OTHERS THEN
[statements]
33
Plsql
PROCEDURES
What is procedure? What is advantages and
disadvantages?
1.
Stored procedures:
a. Stored procedures represent named blocks (as opposed to
anonymous blocks) that are capable of accepting parameters
and work on them.
b. Stored procedures do not have to return a value. Hence,
they cannot be called from inside an SQL statement. Stored
procedures must be executed from a PL/SQL block- named or
anonymous.
d. Merits:
e. Demerits:
34
Plsql
Plsql
PROCEDURES V FUNCTIONS
1. Function is mainly used in the case where it must return a
value. Where as a procedure may or may not return a value or
may return more than one value using the OUT parameter.
2. Function can be called from SQL statements where as
procedure can not be called from the sql statements
3. Functions are normally used for computations where as
procedures are normally used for executing business logic.
4. You can have DML (insert,update, delete) statements in a
function. But, you cannot call such a function in a SQL query.
5. A Function returns 1 value as return type ( If you want more
return values you can declare OUT parameters). Procedure can
return multiple values (max 1024).
36
Plsql
7.Function can be used in dbms_output where as procedure
cannot.
8.Procedure call is a standalone executable statement where as
function call is a part of an executable statement.
Plsql
privileges or not.
Disadvantages of definer rights
But there are problems with the definer rights model as well.
These are explored in the next sections.
Sometimes, your programs should execute using the privileges of
the person running
the program and not the owner of the program. In such cases, you
should choose the invoker rights model.
Rules and restrictions on invoker rights:
Invoker rights resolution of external references will work for the
following kinds
of statements:
SELECT, INSERT, UPDATE, MERGE, and DELETE data
manipulation
Statements.
LOCK TABLE transaction control statement
OPEN and OPEN FOR cursor control statements
EXECUTE IMMEDIATE and OPEN FOR USING dynamic SQL
statements
SQL statements parsed using DBMS_SQL.PARSE
Pass by value, Pass by reference
Whenever we are using modular programming, all languages
supports two types of passing parameter pass-by-value, pass-byreference.
when we are modifying formal parameters, the actual
parameters will be effected or not. In pass-by-value mechanism,
passing values does not change because copy of values are
passed into called program.
If you want to change actual parameters, we are using pass-byreference method. Internally when we are using pass-by-value,
different memory locations are created for corresponding actual,
38
Plsql
formal parameters and also copy of values are passed from actual
to formal parameters.
Whereas in pass-by reference method, a single memory location
is allocated and also only address is passed into formal
parameters.
Oracle also supports these mechanisms when we are using
procedure parameters. By default IN mode is pass-by-reference
and OUT, IN OUT modes are pass-by-value.
Whenever we are returning large amount of data through the OUT
parameter again copy of values are created because internally
this is pass-by-value. To overcome this problem Oracle 8.1
introduced nocopy hint in OUT, IN OUT parameters.
1) IN parameter:
We can pass values to the stored procedure through these
parameters or variables. This type of parameter is a read only
parameter. We can assign the value of IN type parameter to a
variable or use it in a query, but we cannot change its value
inside the procedure.
2) OUT Parameter:
The OUT parameters are used to send the OUTPUT from a
procedure or a function. This is a write-only parameter i.e, we
cannot pass values to OUT parameters while executing the stored
procedure, but we can assign values to OUT parameter inside the
stored procedure and the calling program can recieve this output
value.
39
Plsql
3) IN OUT Parameter:
The IN OUT parameter allows us to pass values into a procedure
and get output values from the procedure. This parameter is used
if the value of the IN parameter can be changed in the calling
program.
By using IN OUT parameter we can pass values into a parameter
and return a value to the calling program using the same
parameter. But this is possible only if the value passed to the
procedure and output value have a same datatype. This
parameter is used if the value of the parameter will be changed in
the procedure.
Plsql
Positional notation
Named notation
Mixed notation
POSITIONAL NOTATION
In positional notation, you can call the procedure as:
findMin(a, b, c, d);
In positional notation, the first actual parameter is substituted for
the first formal parameter; the second actual parameter is
substituted for the second formal parameter, and so on. So, a is
substituted for x, b is substituted for y, c is substituted for z and d
is substituted for m.
NAMED NOTATION
In named notation, the actual parameter is associated with the
formal parameter using the arrow symbol ( => ). So the
procedure call would look like:
41
Plsql
findMin(x=>a, y=>b, z=>c, m=>d);
MIXED NOTATION
In mixed notation, you can mix both notations in procedure call;
however, the positional notation should precede the named
notation.
The following call is legal:
findMin(a, b, c, m=>d);
But this is not legal:
findMin(x=>a, b, c, d);
42
Plsql
the calling program can ignore the parameter values returned by
the subprogram if the subprogram exits with error.
Why is NOCOPY called a hint, not a command?
NOCOPY is called a hint because unlike with a command, it is not
mandatory for the PL/SQL compiler to honor the hint all the time.
How to find out the exact error line number?
If we use SQLERRM in EXCEPTION block than it can show what
exception was raised. We will never know in which line exception
was thrown.
Best approach will be to use combination of SQLERRM and
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE()
Ex:
EXCEPTION WHEN OTHERS THEN
.
vr_sqlerrm := SUBSTR( SQLERRM||
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE(),0,999);
raise_application_error(-20003,EXCEPTION is --> 'vr_sqlerrm);
43
Plsql
44
Plsql
FUNCTIONS
What is a Function in PL/SQL?
A function is a named PL/SQL Block which is similar to a
procedure. The major difference between a procedure and a
function is, a function must always return a value, but a procedure
may or may not return a value.
Advantages of Functions:
The ability to store functions within the Oracle database allows
you to reach great heights in modularity, maintainability, and
performance improvement. Using functions to accomplish specific
tasks improves the reliability of other modules and reduces
development time.
Disadvantages of Funcitons:
You can have DML(insert, update, delete) statements in a
function. But, you cannot call such a function in a SQL query. *Eg:
If you have a function that is updating a table, you can't call that
function in any SQL query.
General Syntax to create a function is
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
45
Plsql
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
PL/SQL Recursive Functions
We have seen that a program or subprogram may call another
subprogram. When a subprogram calls itself, it is referred to as a
recursive call and the process is known as recursion.
46
Plsql
Answer: Here are some function restrictions for all PL/SQL userdefined functions:
1.Deterministic function required: A function must have the
deterministic key word if used with SQL.
2.No updates inserts or deletes from inside DML: A PL/SQL
function is restricted against writing to the database with DML if
the function resides within a DML.
3.No DDL allowed: A function called from inside a SQL statement
is restricted against DDL because DDL issues an implicit commit.
You cannot issue any DDL statements from within a PL/SQL
function.
4.Restrictions against constraints: You cannot use a function in
the check constraint of a create table DDL statement.
5.No commits or IN, OUT parms: When called from within a SQL
query, a function cannot have OUT or IN parameters, and the
function is restricted against using a commit.
1.DETERMINISTIC:
DETERMINISTIC to indicate that the function returns the same
result value whenever it is called with the same values for its
parameters.
We can declare a package-level subprogram DETERMINISTIC in
the package specification but not in the package body.
We cannot declare DETERMINISTIC a private subprogram
(declared inside another subprogram or inside a package body).
2.PIPELINED { IS | USING }:
PIPELINED to instruct the database to return the results of a table
function iteratively. A table function returns a collection type (a
nested table or varray). You query table functions by using the
47
Plsql
TABLE keyword before the function name in the FROM clause of
the query.
If you specify the keyword PIPELINED alone (PIPELINED IS ...), then
the PL/SQL function body should use the PIPE keyword. This
keyword instructs the database to return single elements of the
collection out of the function, instead of returning the whole
collection as a single value.
Parallel Enabled
Parallel enabled table functions can improve performance by
sharing their workload between slave processes. To parallel
enable a function, it must internally define a method for
partitioning the workload, and the following conditions must be
met:
The function must include a PARALLEL_ENABLE clause.
A single REF CURSOR must be specified with a PARTITION BY
clause. Only strongly typed REF CURSORs can be specified in a
PARTITION BY clause that specifies a partition column, but weakly
typed REF CURSORs can be used with the PARTITION BY ANY
clause.
Result cache:
To enable result caching for a function, use the RESULT_CACHE
clause. When a result-cached function is invoked, the system
checks the cache.
If the cache contains the result from a previous call to the
function with the same parameter values, the system returns the
cache result to the invoker and does not re-execute the function
body.
48
Plsql
If the cache not contain the result, the system executes the
function body and adds the result to the cache before returning
control to the invoker.
If function execution results in an unhandled exception, the
exception result is not stored in the cache.
How to use the result cache?
Oracle notes that the result_cache functionality can be enabled in
two ways:
Alter session - you can issue the command "alter session cache
results;" to cache your session data.
PL/SQL - You can create a PL/SQL function using the result_cache
keyword to store the result, and use the new relies_on keyword
to tell Oracle what tables will trigger an invalidation (should the
rows become out-of-date with the current table data).
SQL - You can add the /*+ result_cache */ hint to any SQL
statement, and invoking the result_cache hint is far easier than
creating a PL/SQL array or materialized view because the syntax
is very straightforward:
select /*+ result_cache */
stuff
from tab1 natural join tab2;
Result Cache: Unsupported
EX:
/* File on web: 11g_frc_simple_demo.sql */
FUNCTION betwnstr (
string_in IN VARCHAR2, start_in IN INTEGER, end_in IN INTEGER)
49
Plsql
RETURN VARCHAR2 RESULT_CACHE
Being one of the trump features of Oracle 11g, result cache still
provides no support for
Temporary tables
Sequences
Pseudo columns
Date/Time functions
Table Functions
A table function is a function that can be called from within the
FROM clause of a query.
Perform very complex transformations of data, requiring the use
of PL/SQL, but
need to access that data from within an SQL statement.
Pass complex result sets back to the host (that is, non-PLSQL)
environment. You
can open a cursor variable for a query based on a table function,
and let the host
environment fetch through the cursor variable.
There are two kinds of table functions that merit special mention
and attention in our
50
Plsql
examples:
Streaming table functions
Data streaming means that you can pass from one process or
stage to another
without having to rely on intermediate structures.
Pipelined table functions
These functions return a result set in pipelined fashion, meaning
that data is returned while the function is still executing. Add the
PARALLEL_ENABLE to a
pipelined functions header, and you have a function that will
execute in parallel
within a parallel query.
PACKAGES
What is package specification and package body?
A Package is a database object that groups logically related
PL/SQL types, objects and subprograms. Packages usually have 2
parts - specification & body.
The specification is the interface to our applications; it declares
the types, variables, constants, exceptions, cursors and
subprograms available for use.
51
Plsql
The Body fully defines cursors and subprograms, and so
implements the Specification. Unlike subprograms, packages
cannot be called, passed parameters, or nested.
A Package might include a collection of procedures. Once written,
general-purpose package is compiled, and then stored in an
ORACLE database,
Advantages of Packages:
Modularity: Modularization is the process by which you break up
large blocks of code into smaller pieces (modules) that can be
called by other modules.
Easier Application design: Initially once the Specification has
been compiled, the Body need not be fully defined until one is
ready to complete the application.
Information hiding: Certain procedures can be made as Public
(visible and accessible) and others as Private (hidden and
inaccessible).
Added Functionality: Packaged public variables and cursors
persist for the duration of a session. So, they can be shared by all
procedures that execute in the environment. Also, they allow we
to maintain data across transactions without having to store it in
the database.
Better Performance: When we call a package for the first time,
the whole package is loaded into memory. Therefore, subsequent
calls to related procedures in the package require no disk I/O.
Disadvantages:
52
Plsql
More memory may be required on the Oracle database server
when using Oracle PL/SQL packages as the whole package is
loaded into memory as soon as any object in the package is
accessed.
Updating one of the functions/procedures will invalid other objects
which use different function/procedures since whole package
need to be compiled.
What is the difference b/w public procedure and private
procedure?
Any procedure that is declared and defined ONLY in the package
body is a private procedure. This procedure is local to the
package and other procs cannot call any
private procedure.
if the procedure is declared in the package specification and
defined in the package body it is a public procedure, this is
accessible to other procs also.
Global Variables: The variable defined inside Package
Specification are treated as Global variables, that can be
referenced outside the package and is visible to external users.
Global package items must be declared in the package
specification.
What packages (if any) has Oracle provided for use by
developers?
Oracle provides the DBMS_ series of packages. There are many
which developers should be aware of such as DBMS_SQL,
DBMS_PIPE, DBMS_TRANSACTION, DBMS_LOCK, DBMS_ALERT,
DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL,UTL_FILE.
Local modules can be called only from within the block in which
they are defined; package modules can at a minimum be called
53
Plsql
from anywhere in the package. If the package modules are also
listed in the package specification, they can be called by other
program units from schemas that have EXECUTE authority on that
package.
Question: I have a PL/SQL procedure and I cannot understand
why my output is wrong. How do I debug a PL/SQL program?
Does Oracle have a PL/SQL debugging tool? How can I manually
perform PL/SQL debugging?
Answer: PL/SQL an interpreted language and syntax and
semantic errors are discovered at compile time, and execution
errors are encountered at run time. You may see these types of
PL/SQL errors:
Syntax errors: These are indicated by the "Warning: Procedure
created with compilation errors" message. You can display the
error with the "show errors" SQL*Plus command).
Semantic errors: These are invalid table or column names.
Run time errors: This is a a non-zero Oracle database error
code.
PL/SQL is just like any other procedural language and you can
insert display statements (using dbms_output.put_line) and step
through the code and see exactly how the values of variables are
changing. This is the easiest form of PL/SQL debugging.
Syntax errors: Use the "show errors" command
Use display statements
we can
insert dbms_output.put_line andutl_file.put_line statements to
display variable states. But advanced PL/SQL can be
problematic. The display components of PL/SQL
(dbms_output and utl_file) provide limited PL/SQL debugging
capabilities.
54
Plsql
Use dbms_debug - More complex instrumenting of PL/SQL can
also be accomplished using the dbms_debug online debugging.
Use dbms_profiler - The dbms_profiler package can aid in
PL/SQL debugging.
Conditional Compilation - In Oracle10g, PL/SQL conditional
compilationis ideal for debugging PL/SQL.
PL/SQL debugger - You can use Oracle's PL/SQL debugger (part
of the free SQL Developer suite) to step through the PL/SQL code,
one line at a time, and find any error.
Is it possible to write a package specification without a
package body?
Yes, it is possible to write a package specification without a
package body but not the vice versa. This is specifically used if
there is a package, which is only used for the declaration of public
variables, types, constants, and exceptions. In such case, there is
no need for a package body and only package specification is
enough.
Can a complete package be called?
No, a complete package is not possible to call, invoke, or
parametrize, however, any construct from the package can be
called or invoked.
Is it possible to write a package specification without a
package body? | PL SQL
Yes, it is possible to write a package specification without a
package body but not the vice versa. This is specifically used if
there is a package, which is only used for the declaration of public
variables, types, constants, and exceptions. In such case, there is
55
Plsql
no need for a package body and only package specification is
enough.
56
Plsql
Description
Receives messages from
an alert
Disables notification from
an alert
Removes all alerts for this
session from the
registration list
Sets the polling interval
57
Plsql
SIGNAL Procedure
WAITANY Procedure
WAITONE Procedure
2.DBMS_PIPE
The DBMS_PIPE package lets two or more sessions in the same
instance communicate. Oracle pipes are similar in concept to the
pipes used in UNIX, but Oracle pipes are not implemented using
the operating system pipe mechanisms.
Information sent through Oracle pipes is buffered in the system
global area (SGA). All information in pipes is lost when the
instance is shut down.
Description
Creates a pipe (necessary
for private pipes)
Returns datatype of next
item in buffer
Builds message in local
buffer
NEXT_ITEM_TYPE Function
PACK_MESSAGE Procedures
58
Plsql
PURGE Procedure
RECEIVE_MESSAGE Function
REMOVE_PIPE Function
RESET_BUFFER Procedure
SEND_MESSAGE Function
UNIQUE_SESSION_NAME Function
UNPACK_MESSAGE Procedures
59
Plsql
Information sent through Oracle pipes is buffered in the system
global area (SGA). All information in pipes is lost when the
instance is shut down.
Depending upon wer security requirements, we may choose to
use either a public or a private pipe.
3.DBMS_DEBUG
In order to debug server-side code, it is necessary to have two
database sessions: one session to run the code in debug-mode
(the target session), and a second session to supervise the target
session (the debug session).
ALTER SESSION SET PLSQL_DEBUG = true;
ALTER [PROCEDURE | FUNCTION | PACKAGE | TRIGGER | TYPE]
<name> COMPILE DEBUG;
Description
Notifies the debug session
about the target debugID
CONTINUE Function
Continues execution of the
target program
DEBUG_OFF Procedure
Turns debug-mode off
DEBUG_ON Procedure
Turns debug-mode on
DELETE_BREAKPOINT Function Deletes a breakpoint
DELETE_OER_BREAKPOINT
Deletes an OER breakpoint
Function
60
Plsql
DETACH_SESSION Procedure
DISABLE_BREAKPOINT
Function
ENABLE_BREAKPOINT
Function
EXECUTE Procedure
GET_INDEXES Function
GET_MORE_SOURCE
Procedure
GET_LINE_MAP Function
GET_RUNTIME_INFO Function
GET_TIMEOUT_BEHAVIOUR
Function
GET_VALUE Function
INITIALIZE Function
PING Procedure
PRINT_BACKTRACE Procedure
PRINT_INSTANTIATIONS
Procedure
PROBE_VERSION Procedure
SELF_CHECK Procedure
SET_BREAKPOINT Function
SET_OER_BREAKPOINT
Function
SET_TIMEOUT Function
Plsql
SET_TIMEOUT_BEHAVIOUR
Procedure
SET_VALUE Function
SHOW_BREAKPOINTS
Procedures
SHOW_FRAME_SOURCE
Procedure
SHOW_SOURCE Procedures
SYNCHRONIZE Function
TARGET_PROGRAM_RUNNING
Procedure
4.UTL_FILE
UTL_FILE is available for both client-side and server-side PL/SQL.
Both the client (text I/O) and server implementations are subject
to server-side file system permission checking.
UTL_FILE
Subprograms
Subprogram
FCLOSE Procedure
FCLOSE_ALL Procedure
FCOPY Procedure
FFLUSH Procedure
FGETATTR Procedure
FGETPOS Function
Description
Closes a file
Closes all open file handles
Copies a contiguous portion of a file to
a newly created file
Physically writes all pending output to
a file
Reads and returns the attributes of a
disk file
Returns the current relative offset
62
Plsql
FOPEN Function
FOPEN_NCHAR Function
FREMOVE Procedure
FRENAME Procedure
GET_LINE Procedure
GET_LINE_NCHAR
Procedure
GET_RAW Function
IS_OPEN Function
NEW_LINE Procedure
PUT Procedure
PUT_LINE Procedure
PUT_LINE_NCHAR
Procedure
PUT_NCHAR Procedure
5. DBMS_UTILITY
DBMS_UTILITY Package
Subprograms
Subprogram
ACTIVE_INSTANCES
Procedure
ANALYZE_DATABASE
Procedure
Description
Returns the active instance
Analyzes all the tables, clusters,
and indexes in a database [see
also Deprecated Subprograms]
63
Plsql
ANALYZE_PART_OBJECT
Procedure
ANALYZE_SCHEMA Procedure
Plsql
GET_PARAMETER_VALUE
Function
6.DBMS_JOB:
DBMS_JOB supports multi-instance execution of jobs. By default
jobs can be executed on any instance, but only one single
instance will execute the job. In addition, you can force instance
binding by binding the job to a particular instance. You implement
instance binding by specifying an instance number to the instance
affinity parameter.
DBMS_JOB Package
Subprograms
Subprogram
BROKEN Procedure
CHANGE Procedure
INSTANCE Procedure
INTERVAL Procedure
NEXT_DATE Procedure
REMOVE Procedure
RUN Procedure
SUBMIT Procedure
USER_EXPORT
Procedures
WHAT Procedure
Description
Disables job execution
Alters any of the user-definable
parameters associated with a job
Assigns a job to be run by a instance
Alters the interval between executions
for a specified job
Alters the next execution time for a
specified job
Removes specified job from the job
queue
Forces a specified job to run
Submits a new job to the job queue
Re-creates a given job for export, or
re-creates a given job for export with
instance affinity
Alters the job description for a
specified job
65
Plsql
7.DBMS_OUTPUT
DBMS_OUTPUT
Package
Subprograms
Subprogram
DISABLE Procedure
ENABLE Procedure
GET_LINE Procedure
GET_LINES Procedure
NEW_LINE Procedure
PUT Procedure
PUT_LINE Procedure
Description
Disables message output
Enables message output
Retrieves one line from buffer
Retrieves an array of lines from
buffer
Terminates a line created
with PUT
Places a line in the buffer
Places partial line in buffer
8.DBMS_DDL:
DBMS_DDL Package
Subprograms
Subprogram
ALTER_COMPILE
Procedure
ALTER_TABLE_NOT_REFER
ENCEABLE Procedure
ALTER_TABLE_REFERENCE
ABLE Procedure
Description
Compiles the PL/SQL object
Reorganizes object tables
Reorganizes object tables
66
Plsql
CREATE_WRAPPED
Procedures
IS_TRIGGER_FIRE_ONCE
Function
SET_TRIGGER_FIRING_PR
OPERTY Procedure
Takes as input a
single CREATE OR REPLAC
Estatement that specifies
creation of a PL/SQL package
specification, package body,
function, procedure, type
specification or type body,
generates
a CREATE OR REPLACE stat
ement with the PL/SQL
source text obfuscated and
executes the generated
statement
Returns TRUE if the
specified DML or DDL trigger
is set to fire once. Otherwise,
returns FALSE
Sets the specified DML or
DDL trigger's firing property
9.DBMS_TRANSCATION:
DBMS_TRANSACT
ION Package
Subprograms
Subprogram
ADVISE_COMMIT
Procedure
ADVISE_NOTHING
Procedure
ADVISE_ROLLBACK
Procedure
Description
Equivalent to the SQL statement:
ALTER SESSION ADVISE COMMIT
Equivalent to the SQL statement:
ALTER SESSION ADVISE NOTHING
Equivalent to the SQL statement:
ALTER SESSION ADVISE
ROLLBACK
67
Plsql
BEGIN_DISCRETE_T
RANSACTION
Procedure
COMMIT Procedure
COMMIT_COMMENT
Procedure
COMMIT_FORCE
Procedure
LOCAL_TRANSACTI
ON_ID Function
PURGE_LOST_DB_E
NTRY Procedure
PURGE_MIXED
Procedure
READ_ONLY
Procedure
READ_WRITE
Procedure
ROLLBACK
Procedure
ROLLBACK_FORCE
Procedure
Plsql
Procedure
STEP_ID Function
USE_ROLLBACK_SE
GMENT Procedure
SAVEPOINT <savepoint_name>
Returns local (to local transaction)
unique positive integer that orders
the DML operations of a transaction
Equivalent to the SQL statement:
SET TRANSACTION USE ROLLBAC
K SEGMENT<rb_seg_name>
10.DBMS_LOCK:
DBMS_MVIEW
Package
Subprograms
Subprogram
Description
BEGIN_TABLE_REORGAN Performs a process to
IZATION Procedure
preserve materialized view
data needed for refresh
END_TABLE_REORGANIZ Ensures that the materialized
ATION Procedure
view data for the master table
is valid and that the master
table is in the proper state
ESTIMATE_MVIEW_SIZE
Estimates the size of a
Procedure
materialized view that you
might create, in bytes and
rows
EXPLAIN_MVIEW
Explains what is possible with
Procedure
a materialized view or
potential materialized view
69
Plsql
EXPLAIN_REWRITE
Procedure
I_AM_A_REFRESH
Function
PMARKER Function
PURGE_DIRECT_LOAD_L
OG Procedure
PURGE_LOG Procedure
PURGE_MVIEW_FROM_L
OG Procedure
REFRESH Procedures
REFRESH_ALL_MVIEWS
Procedure
REFRESH_DEPENDENT
Procedures
REGISTER_MVIEW
Procedure
70
Plsql
UNREGISTER_MVIEW
Procedure
71
Plsql
COLLECTIONS
1.What is collections? What are the types of collections?
A collection is an ordered group of elements having the same
data type. Each element is identified by a unique subscript that
represents its position in the collection.
PL/SQL provides three collection types:
72
Plsql
Index-by tables or Associative array
Nested table
Variable-size array or Varray
Varrays:
1. In varrays, elements are the same type and use a sequential
numeric index. This means the index of VARRAY variables is
dense, it means the collection has no gaps between elements.
Before declaring the variable, we know the number of items in
the collection.
2.VARRAY cannot increase in size after it is declared.
3.There are two prototypes for a VARRAY because you can define
it in SQL or PL/SQL also.
4.They are similar to PL/SQL table, and each element in a varray
is assigned a
subscript/index starting with 1.
5.These are dense and Not sparse, which means there is no way
to delete individual elements of a Varray.
The following is the SQL prototype to define a VARRAY of scalar variables:
CREATE OR REPLACE TYPE varray_name AS VARRAY(maximum_size)
OF sql_datatype [NOT NULL];
/
The following prototype defines a VARRAY of any datatype in a PL/SQL block:
TYPE varray_name IS VARRAY(maximum_size) OF [sql_datatype | plsql_datatype]
[NOT NULL];
DECLARE
TYPE number_varray IS VARRAY(10) OF NUMBER;
list NUMBER_VARRAY := number_varray(1,2,3,4,5,6,7,8,NULL,NULL);
BEGIN
FOR i IN 1..list.LIMIT LOOP
dbms_output.put('['||list(i)||']');
END LOOP;
dbms_output.new_line;
END;
/
The program prints the following to the console:
[1][2][3][4][5][6][7][8][][]
73
Plsql
Nested tables:
1.Nested tables are similar to index by table but these can be
stored in database columns but index by tables cannot be stored
in database columns.
2.A Nested table can be considered as a single column table that
can either be in
memory, or as a column in a database table.
3.A nested table is quite similar to a VARRAY with the exception
that the order of the elements is not static.
4.Elements can be deleted or added anywhere in the nested table
where as a VARRAY can only add or delete elements from the end
of the array.
5.Nested Table is known as a sparse collection because a nested
table can contain empty elements.
6.we need to delete or update some elements, but not all the
elements at once.
The index values are not consecutive.
7.We dont have any predefined upper bound for index values.
The following is the SQL prototype to define a nested table of scalar variables:
CREATE OR REPLACE TYPE table_name AS TABLE
OF sql_datatype [NOT NULL];
/
The following prototype defines a nested table of any defined datatype in a PL/SQL block:
TYPE table_name IS TABLE OF [sql_datatype | plsql_datatype]
[NOT NULL];
DECLARE
TYPE number_table IS TABLE OF NUMBER;
list NUMBER_TABLE := number_table(1,2,3,4,5,6,7,8);
BEGIN
list.DELETE(2);
FOR i IN 1..list.COUNT LOOP
IF list.EXISTS(i) THEN
dbms_output.put('['||list(i)||']');
END IF;
END LOOP;
74
Plsql
dbms_output.new_line;
END;
/
The program prints the following to the console: [1][3][4][5][6][7][8]
Plsql
3.Nested table data is stored in a separate store table, a system
generated database table. When we access a nested table , the
database joins the nested table with its store table. This makes
nested tables suitable for queries and updates that only affects
some elements of the collection.
When you choose the associative arrays:
1.A relatively small lookup table, where the collection can be
constructed in memory each time a subprogram is invoked or a
package is initialized.
Passing the collections from database server.
2.Pl/sql automatically converts between host array and
associative array that use numeric key values. The most efficient
way to pass collections to and from the database server is to set
up data values in associative arrays and then use those
associative arrays with bulk constructs (FORALL OR BULK
COLLECT).
What is the difference b/w Nested tables and varrays and
associative arrays?
Differences Between Nested Tables and Varrays
1.Nested tables are unbounded, where as varrays have a
maximum size.
2.Individual elements can be deleted from a nested table, but not
from a varray. Therefore, nested tables can be sparse, whereas
varrays are always dense.
3.Varrays are stored by Oracle in-line (in the same tablespace),
whereas nested table data is stored out-of-line in a store table,
which is a system-generated database table associated with the
nested table.
4.When stored in the database, nested tables do not retain their
ordering and subscripts, whereas varrays do.
76
Plsql
5.Nested tables support indexes while varrays do not support
indexes.
Plsql
SQL?
Usable as
column
datatype in a
table?
Uninitialized
state
Initialization
No
Empty
(cannot be
null);
elements
undefined
Automatic,
when
declared
Sparse?
Yes
Bounded?
No
Can assign
value to any
element at
any time?
Yes
Means of
extending
Assign
value to
element
with a new
subscript
Yes; data
stored "out of
line" (in
separate
table)
Atomically
null; illegal to
reference
elements
Yes; data
stored "in
line" (in same
table)
Via
constructor,
fetch,
assignment
Via
constructor,
fetch,
assignment
Initially, no;
after
deletions, yes
Can be
extended
No; may need
to EXTEND
first
No
Use built-in
EXTEND
procedure (or
TRIM to
condense),
with no
predefined
maximum
78
Atomically
null; illegal to
reference
elements
Yes
No; may need
to EXTEND
first, and
cannot
EXTEND past
upper bound
EXTEND (or
TRIM), but
only up to
declared
maximum
size
Plsql
Collection set operators:
They act and function like SQL set operators in select statements.
The difference is that they are used in assignments between
collections of matching signature types.
They only work with varrays and nested tables because they
require numeric index values.
1.CARDINALITY
The CARDINALITY operator counts the number of elements in a
collection. It makes no attempt to count only unique elements,
but we can combine it with the SET operator to count unique
elements.
The prototype is: CARDINALITY(collection)
Ex:
DECLARE
a LIST := list(1,2,3,3,4,4);
BEGIN
dbms_output.put_line(CARDINALITY(SET(a)));
END;
/
The program now prints the number 4 because there are four unique
elements in the set
derived from the six-element collection.
2. EMPTY
The EMPTY operator acts as an operand, as you would check
whether a variable is null or is not null.
The comparative syntax is: variable_name IS [NOT] EMPTY
3. MEMBER OF
The MEMBER OF operator lets we check if the left operand is a
member of the collection used as the right operand.
Thecomparative syntax is:
variable_name MEMBER OF collection_name
Ex:
DECLARE
TYPE list IS TABLE OF VARCHAR2(10);
n VARCHAR2(10) := 'One';
79
Plsql
a LIST := list('One','Two','Three');
BEGIN
IF n MEMBER OF a THEN
dbms_output.put_line('n is member.');
END IF;
END;
/
The MEMBER OF operator compares and returns a Boolean true type when it
finds the left
operand value in the right operand collection. The left operand datatype
must match the base
datatype of the scalar collection.
4. MULTISET EXCEPT :
The MULTISET EXCEPT operator removes one set from another. It
works like the SQL MINUS set operator.
The prototype is:
collection MULTISET EXCEPT collection
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(4,5,6,7);
BEGIN
dbms_output.put_line(format_list(a MULTISET EXCEPT b));
END;
/
Only the element 4 exists in both sets. The operation therefore removes 4
from the first set.
The following output is generated by the block:
(1, 2, 3)
5. MULTISET INTERSECT
The MULTISET INTERSECT operator evaluates two sets and returns
one set. The return set contains elements that were found in both
original sets. It works like the SQL INTERSECT set
operator.
The prototype is: collection MULTISET INTERSECT collection
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(4,5,6,7);
BEGIN
dbms_output.put_line(format_list(a MULTISET INTERSECT b));
END;
/
80
Plsql
Only one element from both sets matches, and thats the number 4. The
following output is
generated by the block:
(1, 2, 3)
6.MULTISET UNION:
The MULTISET UNION operator evaluates two sets and returns
one set. The return set contains all elements of both sets. Where
duplicate elements are found, they are returned. It functions like
the SQL UNION ALL set operator.
You may use the DISTINCT operator to eliminate duplicates.
The DISTINCT operator follows the MULTISET UNION operator rule.
It functions like the SQL UNION operator.
The prototype is: collection MULTISET UNION collection
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(4,5,6,7);
BEGIN
dbms_output.put_line(format_list(a MULTISET UNION b));
END;
/
o/p: (1, 2, 3, 4, 4, 5, 6, 7)
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(4,5,6,7);
BEGIN
dbms_output.put_line(format_list(SET(a MULTISET UNION b)));
END;
/
Both the DISTINCT and SET operators produce the following output:
(1, 2, 3, 4, 5, 6, 7)
7. SET
The SET operator removes duplicates from a collection, and
thereby creates a set of unique values. It acts like a DISTINCT
operator sorting out duplicates in a SQL statement.
The operator prototype is:
SET(collection)
we can also use the SET operator as an operand, as you would
check whether a variable is null or is not null.
The comparative
81
Plsql
syntax is:
DECLARE
a LIST := list(1,2,3,3,4,4,5,6,6,7);
BEGIN
dbms_output.put_line(format_list(SET(a)));
END;
/
The original set contains ten elements, but three are duplicated. The SET
operator removes all
duplicates and generates a new set with seven unique elements.
(1, 2, 3, 4, 5, 6, 7)
You can also use SET as an operand in comparison statements:
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(1,2,3,3,4,4);
c LIST := list();
FUNCTION isset (set_in LIST) RETURN VARCHAR2 IS
BEGIN
IF set_in IS A SET THEN
IF set_in IS NOT EMPTY THEN
RETURN 'Yes - a unique collection.';
ELSE
RETURN 'Yes - an empty collection.';
END IF;
ELSE
RETURN 'No - a non-unique collection.';
END IF;
END isset;
BEGIN
dbms_output.put_line(isset(a));
dbms_output.put_line(isset(b));
dbms_output.put_line(isset(c));
END;
8.SUBMULTISET
The SUBMULTISET operator identifies if a set is a subset of
another set. It returns true when the left operand is a subset of
the right operand. The true can be misleading if youre looking for
a proper subset, which contains at least one element less than
the superset.
82
Plsql
The function returns true because any set is a subset of itself.
There is no test for a proper subset without also using the
CARDINALITY operator to compare whether the element counts of
both sets are unequal.
The prototype is: collection SUBMULTISET OF collection
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(1,2,3,3,4,5);
c LIST := list(1,2,3,3,4,4);
BEGIN
IF a SUBMULTISET c THEN
dbms_output.put_line('[a] is a subset of [c]');
END IF;
IF NOT b SUBMULTISET c THEN
dbms_output.put_line('[b] is not a subset of [c]');
END IF;
END;
/
It prints
[a] is a subset of [c]
[b] is not a subset of [c]
Collection methods
1.COUNT
The COUNT method returns the number of elements with
allocated space in VARRAYand NESTED TABLE datatypes.
The COUNT method returns all elements in associativearrays. The
return value of the COUNT method can be smaller than the return
value of LIMIT for the VARRAY datatypes.
It has the following prototype: pls_integer COUNT
2.DELETE
The DELETE method lets you delete members from the collection.
It has two formal parameters; one is mandatory and the other is
optional. Both parameters accept PLS_INTEGER, VARCHAR2, and
LONG variable types.
Only one actual parameter, n, is interpreted as the index value to
delete from the collection. When you supply two actual
parameters, the function deletes everything from the parameter n
to m, inclusively.
83
Plsql
It has the following prototypes:
void DELETE(n)
void DELETE(n,m)
3.EXISTS
The EXISTS method checks to find an element with the supplied
index in a
collection. It returns true when the element is found and false
otherwise. The
element may contain a value or a null value. It has one
mandatory parameter, and the parameter can be a PLS_INTEGER,
VARCHAR2, or LONG type. It has the following
prototype:
boolean EXISTS(n)
4.EXTEND
The EXTEND method allocates space for one or more new
elements in a VARRAY
or NESTED TABLE collection. It has two optional parameters. It
adds space for
one element by default without any actual parameter. A single
optional parameter designates how many physical spaces should
be allocated, but it is constrained by
the LIMIT value for VARRAY datatypes. When two optional
parameters are provided, the first designates how many elements
should be allocated space and the second designates the index it
should use to copy the value to the newly allocated space. It
has the following prototypes:
void EXTEND
void EXTEND(n)
void EXTEND(n,i)
5.FIRST
The FIRST method returns the lowest subscript value in a
collection. It can return a PLS_INTEGER, VARCHAR2, or LONG
type.
It has the following prototype: mixed FIRST
6.LAST
84
Plsql
The LAST method returns the highest subscript value in a
collection. It can return a PLS_INTEGER, VARCHAR2, or LONG type.
It has the following prototype: mixed LAST
7.LIMIT
The LIMIT method returns the highest possible subscript value in
a collection. It can only return a PLS_INTEGER type and can only
be used by a VARRAY datatype. It has the following prototype:
mixed LIMIT
8.NEXT(n)
The NEXT method returns the next higher subscript value in a
collection when
successful or a false. The return value is a PLS_INTEGER,
VARCHAR2, or LONG type.
It requires a valid index value as an actual parameter.
It has the following prototype: mixed NEXT(n)
9.PRIOR(n)
The PRIOR method returns the next lower subscript value in a
collection when
successful or a false. The return value is a PLS_INTEGER,
VARCHAR2, or LONG type.
It requires a valid index value as an actual parameter.
It has the following prototype: mixed PRIOR(n)
10.TRIM
The TRIM method removes a subscripted value from a collection.
It has one optional parameter. Without an actual parameter, it
removes the highest element form the array.
An actual parameter is interpreted as the number of elements
removed from the end of the collection.
It has the following prototypes:
void TRIM
void TRIM(n)
Collection Exceptions:
85
Plsql
1.COLLECTION_IS_NULL: An attempt to use a null collection.
2.NO_DATA_FOUND: An attempt to use a subscript that has
been deleted or is a
nonexistent unique string index value in an associative array.
3.SUBSCRIPT_BEYOND_COUNT:
An attempt to use a numeric index value that is higher than the
current maximum number value. This error applies only to varrays
and nested tables. Associative arrays are not bound by the
COUNT return value when adding new elements.
4.SUBSCRIPT_OUTSIDE_LIMIT:
An attempt to use a numeric index value outside of the LIMIT
return value. This error only applies to varrays and nested tables.
The LIMIT value is defined one of two ways. Varrays set the
maximum size, which becomes their limit value. Nested tables
and associative arrays have no fixed maximum size, so the limit
value is set by the space allocated by the EXTEND method.
5.VALUE_ERROR:
An attempt is made to use a type that cannot be converted to a
PLS_INTEGER, which is the datatype for numeric subscripts.
Functions can be used in collections?
EXISTS, COUNT, LIMIT, FIRST, LAST, PRIOR, and NEXT are
functions that check the properties of a collection or individual
collection elements. EXTEND, TRIM, and DELETE are procedures
that modify a collection.
Plsql
. Bulk binds improve performance by minimizing the number of
context switches between the PL/SQL and SQL engines. With bulk
binds, entire collections, not just individual elements, are passed
back and forth.
The keyword FORALL instructs the PL/SQL engine to bulk-bind
input collections before sending them to the SQL engine. Although
the FORALL statement contains an iteration scheme.
In a FORALL statement, if any execution of the SQL statement
raises an unhandled exception, all database changes made during
previous executions are rolled back. However, if a raised
exception is caught and handled, changes are rolled back to an
implicit save point marked before each execution of the SQL
statement. Changes made during previous executions are not
rolled back. The following restrictions apply to the FORALL
statement:
You can use the FORALL statement only in server-side programs
(not in client-side programs).Otherwise, you get the error this
feature is not supported in client-side programs.
The INSERT, UPDATE, or DELETE statement must reference at
least one collection.
What is Bulk Collect?
The keywords BULK COLLECT tell the SQL engine to bulk-bind
output collections before returning them to the PL/SQL engine.
We can use these keywords in the SELECT INTO, FETCH INTO, and
RETURNING INTO clauses. The FORALL statement is specifically
used for processing DML (INSERT, DELETE, and UPDATE)
statements to improve performance by reducing the overhead of
SQL processing.
87
Plsql
The PL/SQL interpreter executes all procedural statements.
However, all SQL statements in the PL/SQL block are sent to the
SQL engine, which parses and executes them.
The PL/SQL-to-SQL context switch adds some overhead, which
could become significant when SQL statements are nested in
loops.
Context-Switching:
Context-switching is an almost-irreducible cost of computing that
occurs in CPUs, operating systems, and software.
we specifically refer to the exchange of processing control
between the SQL and PL/SQL engines. These two engines are
separate and distinct but we use them interchangeably. This
means that when we call SQL from PL/SQL or vice versa, the
calling context needs to store its process state and hand over
control and data to its counterpart engine (which may or may not
be picking up from an earlier switch). This switching cycle is
computationally intensive and can
typically be repeated so many times that its effects on response
times can become quite noticeable.
BULK BIND USING FORALL LOOP:
The FORALL systax allows us to bind the contents of collection to
a single DML statement, allowing the DML to be run for each row
in the collection without requiring a context switch each time.
FORALL loop improves performance of BULK INSERT, BULK
UPDATE, BULK DELETE.
FORALL loop allows only statement and that must be DML
statement.
Systax:
FORALL <VAR> IN <LOWER BOUND>..<UPPER BOUND>
DML STATEMENT
SQL%BULK ROW COUNT:
88
Plsql
The SQL%BULK ROW COUNT cursor attributes gives information
about the rows affected by each iteration of the FORALL
statement.
SAVE EXCEPTIONS AND SQL%BULK EXCEPTIONS:
1.FORALL loop improves the performance of BULK INSERT, BULK
UPDATE, BULK DELETE. If there no exception handler, all the work
done by the current bulk operation is rolled back.
2.If there is an exception handler, the work done prior to the
exception is kept, but no more processing is done.
3.Neither of these situations is very sastifactory, so instead we
should use the SAVE EXCEPTION clause to capture the exception
and allow us to continue past them. We can use the SQL
%BULKEXCEPTION in exception part.
VS
BULK COLLECT
Plsql
3.First, if you expect to retrieve a relatively small number of rows
(in the hundreds at most), a cursor FOR loops performance in
Oracle Database 10g and above will likely meet your
requirements. Oracle Database automatically optimizes cursor
FOR loops to execute similarly to BULK COLLECT, so you get most
of the advantages of that approach.
4.Next, if youre writing a program that is run only occasionally
and is not in the critical path of operations, you may want to
choose the simplicity and readability of the cursor FOR loop over
the incremental improvement in performance (and additional
complexity of code) that BULK COLLECT offers.
Use an implicit SELECT INTO for single-row fetches. Developers
often tell me that they write a cursor FOR loop to fetch a single
row. Why not? Oracle Database does so much of the work for you,
saving several lines of code and several minutes of typing.
But theres a problem with using a cursor FOR loop for a singlerow fetch: the resulting code is very misleading. It looks like you
expect to retrieve multiple rows, yet you get just one.
If you need to retrieve a single row and you know that at most
one row should be retrieved, you should use a SELECT INTO
statement.
Bulk collect:
Using bulk collect into a collection will be faster, but talking about
that amount of records, it could be also dangerous because of the
per-session memory it would consume.
In this case you could use the LIMIT clause, to fetch only a smaller
group of records, process them, and then fetch another group.
Disadvantages of bulk collect:
90
Plsql
Using the BULK COLLECT clause in PL/SQL implies following
restrictions:
1.We cannot bulk collect into an associative array having a string
type for the key.
2.BULK COLLECT clause can be used only in server-side programs
(not in client-side programs) else, error is reported that it is not
supported in client-side programs.
3.Collections should be used as target variables listed in a BULK
COLLECT INTO clause.
4.Composite targets (such as objects) cannot be used in the
RETURNING INTO clause else error is reported for feature with
RETURNING clause.
5.Multiple composite targets cannot be used in the BULK COLLECT
INTO clause When implicit data type conversions are needed.
6.When an implicit datatype conversion is needed, a collection of
a composite target (such as a collection of objects) cannot be
used in the BULK COLLECT INTO clause.
Thus above mentioned points should be kept in mind while using
BULK COLLECT.
What is collections? What is the use of LIMIT clause in bulk
collect?
Using LIMIT with BULK COLLECT
Oracle provides a LIMIT clause for BULK COLLECT that allows you
to limit the number of rows fetched from the database. The
syntax is:
FETCH cursor BULK COLLECT INTO ... [LIMIT rows];
91
Plsql
where rows can be any literal, variable, or expression that
evaluates to an integer (otherwise, the database will raise a
VALUE_ERROR exception).
LIMIT is very useful with BULK COLLECT, because it helps you
manage how much memory your program will used to process
data. Suppose, for example, that you need to query and process
10,000 rows of data. You could use BULK COLLECT to retrieve all
those rows and populate a rather large collection. However, this
approach will consume lots of memory in the PGA for that session.
If this code is run by many separate Oracle schemas, your
application performance may degrade because of PGA swapping.
FORALL loop_counter IN bounds_clause
SQL_STATEMENT [SAVE EXCEPTIONS];
where bounds_clause is one of the following:
lower_limit..upper_limit
INDICES OF collection_name BETWEEN lower_limit..upper_limit
VALUES OF collection_name
THE INDICES OF OPTION
As stated previously, the INDICES OF option enables you to loop
through a sparse collection.
Recall that such a collection may be a nested table or an
associative array.
THE VALUES OF OPTION
VALUES OF..., references values of the individual elements
of a particular collection, which is either a nested table or an
associative array.
The elements of the collection used in the VALUES OF clause must
be PLS_INTEGER or BINARY_INTEGER.
Why there is such a huge performace difference between
Collection loop and a cursor Loop? Why collection
populated using Bulk collect is way faster?
92
Plsql
PL/SQL sends SQL statements such as DML and queries to the
SQL engine for execution, and SQL returns the results to PL/SQL.
You can minimize the performance overhead of this
communication between PL/SQL and SQL by using the PL/SQL
features that are known collectively as bulk SQL.
The FORALL statement sends INSERT, UPDATE, or DELETE
statements in batches, rather than one at a time. The BULK
COLLECT clause brings back batches of results from SQL. If the
DML statement affects four or more database rows, bulk SQL can
improve performance considerably.
Bulk SQL uses PL/SQL collections to pass large amounts of data
back and forth in single operations. This process is called bulk
binding. If the collection has n elements, bulk binding uses a
single operation to perform the equivalent of n SELECT INTO,
INSERT, UPDATE, or DELETE statements. A query that uses bulk
binding can return any number of rows, without requiring a FETCH
statement for each one.
What is BULK LOADER?
BulkLoader scans a directory structure containing content and
loads it into a specified content repository. In addition to loading
content, BulkLoader reads prepared metadata files and associates
the metadata with each loaded content item. Metadata files can
be prepared for each specific content item, or more broadly for
directories and subdirectories of items.
If you use BulkLoader to load content into a database repository,
then both the metadata and binary files are transferred to the
repository. If you load into a filesystem repository, then only the
metadata is transferred to the database--the actual content files
remain in place on the filesystem.
You cannot use the Bulkloader to update existing content (or its
metadata) within a filesystem repository. It can only be used to
add new content to the repository.
93
Plsql
DYNAMIC SQL
Native Dynamic SQL (EXECUTE IMMEDIATE)
DBMS_SQL
Supports
DESCRIBE_COLUMNS
Supports bulk
Dynamic SQL.
94
Plsql
Only supports Single row
Updates/Deletes with
RETURNING clause.
95
Plsql
96