You are on page 1of 75

882 OracleS PUSQL Programming

he words listed in this appendix are reservgd by pLlSeL.


Reserved words have special syrrtactic meaning to the
language and thus can't be used as identifiers (for variable
names/ procedure names, and so on). Some of these words
are reserved by SQL as well. These words can't be used to
name database objects such as tables, sequences, and views.
The following table lists the reserved words for PL/SeL, up to and
including version B. Not all of these words are reserved by earlier versions,
but their use should be avoided since they will conflict in version B.

ABORT ACCEPT ACCESS* ADD*


ALL* ALTER* AND* ANY*
ARRAY ARRAYLEN AS* ASC*
ASSERT ASSICN AT AUDIT*
AUTHORIZATION AVC BASE TABLE BECIN
BETWEEN* BINARY INTECER BODY BOOLEAN
BY* CASE CHAR* CHAR BASE
CHECK* CLOSE CLUSTER* CLUSTERS
COLAUTH COLUMN* COMMENTX COMMIT
COMPRESS* CONNECT* CONSTANT CRASH
CREATE* CURRENT* CURRVAL CURSOR
DATABASE DATA BASE DATEX DBA
DEBUGOFF DEBUCON DECLARE DECIMAL*
DEFAULT* DEFINITION DELAY DELETE*
DESC* DICITS DISPOSE DISTINCT*
DO DROP* ELSE* ELSIF
END ENTRY EXCEPTION EXCEPTION INIT
EXCLUSIVE* EXISTS* EXIT FALSE
.FETCH
FI LE* FLOAT* FOR*
FORi\4* FROM* FUNCTION GENERIC
COTO CRANT* CROUP* HAVINC*
IDENTIFIED* IF IMMEDIATE* lN*
INCREMENT* INDEX* INDEXES INDICATOR

*Also reserved by 5QL.


Appendix A: PUSQL Reserved Words 883

INITIAL+ I NSERT* INTECER* INTERFACE


INTERSECT* INTO* ls* LEVEL*
LIKE* LIMITED LOCK* LONC*
LOOP MAX MAXEXTENTS* MIN
MINUS MLSLABEL MOD MODE*
NATURAL NATURALN NEW NEXTVAL
NOAUDIT* NOCOMPRESS* NOT* NOWAIT*
NULL* NUMBER* NUMBER BASE oF*
OFFLINE* oN* ONLINE* OPEN
OPTION* oR* ORDER* OTHERS
OUT PACKACE PARTITION PCTFREE*
PLS INTECER POSITIVE POSITIVEN PRACMA
PRIOR* PRIVATE PRIVILECES* PROCEDURE
PUBLIC* RAISE RANCE RAW*
REAL RECORD REF RELEASE
REMR RENAME* RESOURCE* RETURN
REVERSE REVOKE* ROLLBACK ROW*
ROWID* ROWLABEL+ ROWNUM ROWS*
ROWTYPE RUN SAVEPOINT SCHEMA
SELECT* SEPARATE SESSION* SET*
SHARE* SMALLINT* SPACE SQL
SQLCODE SQLERRM STATE* STATEMENT
STTDEV SUBTYPE SUCCESSFUL* SUM
SYNONYM* SYSDATE* TABAUTH TABLE*
TABLES* TASK TERMINATE THEN*
TO* TRICCER* TRUE TYPE
UID* UNION* UNIQUE* UPDATE*
USE USER* VALIDATE* VALUES*
VARCHAR* VARCHAR2X VARIANCE VIEW*
VIEWS WHEN WHENEVER* WHERE*
WHILE WITH* WORK WRITE
XOR
*Also reserved by SQL.
884 OracleS PUSQL Programming

lf you want to use a reserved word, it must be enclosed in double


quotation marks" For example, the following block is legal:
, DECLARE
"BEG]N" NUMBER;
BEG]N
'BEGIN" := 7;
END;

Although this is legal, it is not recommended. For more information, see


Chapter 2.
888 OracleS PUSQL Programming

his appendix catalogs the built-in packages that are


available for use with PLISQL. Each package is described
briefly, including the syntax for the procedures and
functions within it.

Creating the Packages


All of the supplied packages are owned by the database user SYS. There are
public synonyms for them as well, so they can be called without prefixing
SYS to the package name. EXECUTE permission on the package is
necessary for users other than SYS to call the procedures and functions
within the packages. The script that creates the data dictionary, catproc.sql,
also creates these packages. You can look online in your Oracle system to
find additional information-the individual packages are created in
separate files. The location of the files is system dependent; for example, on
Unix systems they are usually located in the
$ORACLE_HOMEirdbms/admin directory. The files to create each
package contain comments which provide further information about how
to use them.
Each package is typically stored in two files on the operating system-
one for the package header, and one for the body. The body is normally
shipped in wrapped format.
The packages described in this appendix are listed in Table B-i.

Package Descriptions
Each of the supplied packages is described in the following sections.
The procedures and functions are described following a general
introduction to the package itself. Some of the packages, or the procedures
within the packages, are available in certain PLiSQL releases only. This
is also indicated.

DBMS ALERT
The DBMS_ALERT package is used to send messages between sessions
connected to the same database. Alerts are synchronous, meaning that they
are sent when the transaction commits. lf the transaction rolls back, the
alert is not sent. For more information on alerts, see Chapter 16.
Appendix B: Guide to Supplied packages
BB9

PackageName Description
DBMS-ALERTI Synchronous inter-session communication
DBMS-APPL|CAT|ON lNFo Allows registering of an application for
tracing purposes
DBMS-AQ & DBMS-AQADM Management of the oracre8 Advanced
Queuing option
DBMS_DEFER, Allows you to build and administer
DBMS_DEFER_SYS & deferred remote procedure calls
DBMS_DEFER-QUERY2
DBMS_DDL pLlSeL equivalents for some DDL
commands
DBMS_DESCRIBE Describes stored subprograms
DBMSJOBT Allows scheduling of pLlSeL procedures
DBMS_LOB Manipulation of Oracle8 LOBs
DBMS_LOCK User-defined locks
DBMS-ourPUTl provides screen output in sel*plus or
Server Manager
DBMS-PIPE' Asynchronous inter-session
communication
DBMS_REFRESH & Allows you to manage snapshots
^
DBMS SNAPSHOT2
DBMS_REPCAT, Management of Oracle,s symmetric
DBMS_REPCAT_AUTH & replication facility
DBMS-REPCAT-ADMIN2
DBMS-RowlD2 Allows you to obtain information from a
ROWID, and to convert between aracleT
and Oracle8 ROWIDs

TABLE B- 1. Packages Supptied with pL/SeL

lThis package is discussed in


earlier chapters; only a brief description is included in this
Appendix.

24 complete
discussion of this package is beyond the scope of this book; only a brief
description is included in this Appendix.
890 OracleS PUSQL programming

Package Name Description


DBMS SESSION PL/SQL equivalents for ALTER SESSTON
DBMS_SHARED-POOLI Control of the shared pool
DBMS_SQLl Dynamic PL/SQL and SQL
DBMS_TRANSACTION Transaction management commands
DBMS UTILITY Additional uti lity procedures
UTL FILEl Provides File l/O

TABLE B- 1. Packages Supptied with pL/SeL (continued)


lThis package is discussed in earlier chapters; only a brief description is included in this
Appendix.

24 complete
discussion of this package is beyond the scope of this book; only a brief
description is included in this Appendix.'

DBMS_APPLICATION INFO

SET MODULE
This procedure is used to set the value of module for the current session,
and can also be used to set the action. lt is defined with
Appendix B: Guide to Supplied Packages 89 I

P ROC E D U RE S ET_MO D ULE(mod u I e_n a me I N VA RC HAR2,


action-name I N VARCHAR2);

where module_name is the name of the currently running module, and


action nameis the name of the current action. The module is limited to 48
bytes, and the action to 32 bytes-longer values will be truncated.

READ MODULE
This procedure is used to read the values of module and action for the
current session. This information can also be determined by querying
v$session, but by default only users with the DBA privilege can directly
read the table. READ MODULE is defined with

P ROC E D U RE REA D_MO DULE(mod u I e_n ame OUT VARC H AR2,


action-iame OUT VARCHAR2);

where module_name is the last value set for module using SET_MODULE,
and action_name is the last value set for action using SET_MODULE or
SET ACTION.

SET ACTION
SET_ACTION is used to just set the value of the action field for the current
session. lt should be used before entering a section of your program, and is
defined with

P ROCE D U RE SET_ACTI O N (action_name I N VA RC HAR2 ) ;

where action_name is the name of the current action. action_name is


limited to 32 bytes-longer values will be truncated. When your program is
finished with this section, it is a good idea to set the action to NULL.

SET CLIENT INFO


This procedure is used to record the value of client_info in v$session for
the current session. Oracle does not use this value, but it can be queried by
the DBA. One possible use is the name of the current user, or their
machine name as identified by the client program. lt is defined with
892 Oracle8 PUSQL programming

PRocE D u RE s ET-cLr E NT-r N Fo(c/i e nt_i nfo r N VARCHAR2);

where client-info is the new value for the field. lt is limited to


64 bytes, and
longer values will be truncated.

READ_CLIENT INFO
READ-CL|ENT-|NFo will rerurn the varue last set with sET cltENT
tNFo.
It is defined with

PRocE D u RE READ_CL I E NT_r N Fo (c I i e nt_i nfo o ur VARC HAR2);

where client-info is the last value set using sET_cLrENT_|NFo.

DBMS_AQ and DBMS_AQADM


These packages are used to admilister the oracre Advanced
ElEt
Queuing system. ?B_MS-Aa imprements the enqueue and dequeue
operations for queues, and DBMS_AeADM allows you io administer
queues and queue tables. For more information, seechapter i7.

DBMS_DEFER, DBMS_DEFER SYS


and DBMS-DEFER_QUERY
These packages allow you to build and administer deferred remote
rrc-rri' procedure calls. A full discussion of
these
packages is beyond the
scope of this book, For more information, see oratdeT sZrver Replication.

DBMS DDL
The DBMS_DDL package provides pLlSeL equivalents of some useful
DDL
commands which cannot.be used directly in pL/SeL. Although the
?PM:_I9L package can be used to execure these commandi as well,
DBMS_DDL provides a simpler syntax.

ALTER_COMPILE
This procedure is equivalent to the sel commands ALTER pRocEDURE
COMPILE, ALTER PACKACE COi\4PILE, ALTER PACKAGE BODY
COMPILE, and ALTER FUNCTTON COMptLE. The syntax is
Appendix B: Guide to Supplied Packages 893

PROCEDU RE ALTER-COMPI LE(


type VARCHAR2,
schema VARCHAR2,
name VARCHAR2);

The parameters are described in the following table. ALTER_COMPILE can


raise any of the following errors:

I ORA-20000: lnsufficient privileges or object does not exist.


I ORA-20001: Remote object, cannot compile.
I ORA-20002: Bad value for object type.

Parameter Type Description


type VARCHAR2 Type of object to compile. Must be
one of 'PROCEDURE',
,FUNCTION"'PACKACE"
OT
,PACKACE
BODY'.
schema VARCHAR2 Schema that owns the object. This
is case sensitive.
name VARCHAR2 Name of the object to compile.
Also case sensitive.

ANALYZE_OBJECT
This procedure is equivalent to the SQL commands ANALYZE TABLE,
ANALYZE CLUSTER, or ANALYZE INDEX. The syntax is

PROCEDU RE ANALYZE-OBJ ECT (

type VARCHAR2,
schema VARCHAR2,
name VARCHAR2,
method VARCHAR2,
estimate rows NUMBER DEFAULT NULL,
esti mate4ercent NUMBER DEFAU LT NU LL);

The parameters for ANALYZE-OBJECT are described in the following table.


894 OracleS PUSQL programming

Parameter Type Description


type VARCHAR2 Type of object to analyze. Should
be one of 'TABLE', 'CLUSTER,, or
,INDEX'.
schema VARCHAR2 Schema that owns the object. This
parameter is case sensitive.
name VARCHAR2 Name of the object to analyze.
This parameter is also case
sensitive.
method VARCHAR2 Analyze method-NULL or
,ESTIMATE'.
If 'ESTIMATE" thCN
one of estimate rows or
esti m ate_percent must be non-zero.
estimate_rows NUMBER Number of rows to estimate.
estimate_percent NUMBER Percentage of rows to estimate. lf
estimate rowsis non-zero, this
parameter is ignored.

DBMS_DESCRIBE

TYPE varchar2_table tS TABLE OF VARCHAR2(30)


INDEX BY BINARY-INTECER;
TYPE number_table tS TABLE OF NUMBER
INDEX BY BINARY-INTECER;

DESCRIBE_PROCEDURE
PROCEDURE DESCRI BE_PROCEDURE (
object_name I N VARCHAR2,
reservedl lN VARCHAR2,
Appendix B: Guide to Supplied Packages
895

reserved2lN VARCHAR2,
overload OUT numberlable,
positi on OUT nu mberJable,
levelOUT numberlable,
argu ment_name OUT varchar2_table,
datatype OUT numberlable,
defau lt_va lue OUT number1able,
i n_out OUT numberlable,

length OUT numbelable,


precision OUT numberlable,
scale OUT number_table,
radix OUT numberJable,
spare OUT number1able);

The procedure that is to be described is specified by object_name.


lnformation about each parameter is returned in the pl/sel tables. For
example, the name of the first parameter is in argument_namd1), and its
datatype is in datatype(1). The name of the second parameter is in
argument_namd2), and so on. The OCI procedure odessp provides the
same functionality as DBMS_DESCR|BE. The parameters are described in
the following table.

Parameter Datatype Description


object-name VARCHAR2 Procedure or function to describe.
Can be owned by a different schema,
or be in a package.
reservedl VARCHAR2 Not used currently. pass as NULL.
reserved2 VARCHAR2 Not used currently. pass as NULL.
overload numberJable Sequence number for overloaded
procedures. lnformation about the
first version has overload = 0, the
second has overload = 1, and so on.
position number table Position within the argument list.
Function return values have
position 0.
895 OracleS PUSQL Programming

Parameter Datatype Description


level number table For composite types such as a record
or table, level increases by 1 with
each level of nesting. lf a record
declaration is at level 2, then the
fields within the record will be at
level 3.
a rgu mp nt_name varch a r2_tab e
I Narne of this parameter.
datatype numbelable Datatype code for this parameter.
Available values are listed in Table
B-2. Note that subtypes are returned
the same as their base type-
INTECER and REAL are subtypes of
NUMBER, and thus would return 2.
defauli-value number table 'l if the argument has a default value,
0 otherwise.
in_out number table lndicates the mode of the parameter.
0 means lN, 1 means OUT, and 2
signifies lN OUT.
length numbelable Length of the argument (for CHAR or
VARCHAR2).
prectston number table Precision of the argument (for
NUMBER).
scale number table Scale of the argument (for NUMBER).
radix number table Radix of the argument (for NUMBER).
spare number table Not currently used-this parameter is
reserved for future functional ity.

DBMSJOB
The DBMSJOB package is used to schedule PL/SQL jobs to run in
the background. Jobs are scheduled to run at certain times by
background processes. A job is just a stored procedure. lf a job fails,
PL/SQL will try up to 16 times to run the jo.b again until it succeeds. For
more information, see Chapter 18"
Appendix B: Guide to Supplied packages gg|

Datatype Value Meaning


1 VARCHAR2
2 NUMBER
3 BINARY INTECER
B LONC
11 ROWID
12 DATE
23 RAW
24 LONC RAW
96 CHAR
106 MLSLABEL
250 PVSQL Record
251 PL/SQL Table
252 BOOLEAN

TABLE B-2. Datatype Codes used for DBMS_DESCRiBE


.DESCRIBE PROCEDURE

DBMS LOB
DBMS_LOB is used to manage the four types of Oracle8 large
objects - CLOBs, BLOBs, NCLOBs, and BFlLEs. There are alio
oracle8 oCl functions which are equivalent to the functionality in the
DBMS_LOB package. For more information, see Chapter 21.

DBMS_LOCK
The DBMS-LOCK package is used to create your own user-defined locks.
These locks are managed the same way as other oracle locks. This means
that they can be viewed in the fixed views in the data dictionary. User
locks are prefixed with 'UL' so they do not conflict with oracle locks. For
more information on the DBMS_LOCK package, see the oracle server
Application Developer's Guide and the Oracle ServEr Reference.
898 OracleS PUSQL Programming

Several of these procedures use lock modes, which are specified by


number. These numbers and their meanings are listed in Table B-3.

ALLOCATE_UNIQUE
This procedure will generate a unique lock lD from a lock name. The
syntax rs

PROCEDU RE ALLOCATE-U N IQU E(

lockname lN VARCHAR2,
lockh and e OUT VARCHAR2,
I

expiration secs lN INTECER DEFAULT 864000);

A handle to the lock lD is returned in lockhandle, which can be up to 128


bytes. Lock lDs are numbers rangingfrom 01o1O73741823. Either lock lDs
or lock handles are used in subsequent calls. This procedure always issues
a COMMIT. expiration_secs specifies the minimum time before the lock is
subject to cleanup, in seconds.

CAUTION
Lock names beginning with ORA$ are
reserved for use by Oracle. The lock name
has a maximum length of 128 bytes and is
case sensitive.

ldentifier Meaning
1 Null mode
2 Row Share mode (ULRS)
3 Row Share Exclusive mode (ULRX)
4 Share mode (ULS)
5 Share Row Exclusive mode (ULRSX)
6 Exclusive mode (ULX)

TABLE B-3. Lock Mnde ldentifiers


Appendix B: Guide to Supplied packages
899

REQUEST
FUNCTION REQUEST(,d lN INTEGER,
lockmode lN INTECER DEFAULT X MODE,
timeout lN INTECER DEFAULT MAXWA|T,
release on commit lN BOOLEAN DEFAULT FALSE)
RETURN INTECER;
FUNCTION REQUEST(/ockhandle tN VARCHAR2,
lockmode lN INTECER DEFAULT X MODE,
timeout lN INTECER DEFAULT MAX\ryAtT,
release_on_commit lN BOOLEAN DEFAULT FALSE)
RETURN INTECER;

This function is used to request a lock with a particurar mode. lt is


overloaded on the first parameter-the lock handle or lock lD. The
parameters and return values are described in the following tables.

Parameter Type Description


id INTECER Lock lD of the lock to request.
Ranges from 0 Io 1073741823.
lockhandle VARCHAR Lock handle, as returned by
ALLOCATE_U N IQU E. Either
lockhandle or idshould be
specified, but not both.
lockmode INTECER Lock nrode to reqLlest. Valid values
are listed in Table B-3.
tinteout INTECER N4axilt-rur-n tirle (in seconds) to w.rit
for the lock to be granted. lf the
lock can't be granted rvithin this
period, REQUEST rerurns l.
rele.l-se on contntit BOOLE,\N lf TRUE, tlre lock vvill be rele..tsed
vu herr tlte tr.'lrrs.'lctiorr issues .r

CON1N1lT. lf FALSE, the locL is held


until it is erplicitlv released.
900 OracteS pUSeL programming

REQUEST Return Value Meaning


0 5uccess
1 limeout
2 Deadlock detected
3 Parameter error
4 Already own the lock
5 lllegal lock handle

CONVERT
FUNCTION CONVERT('d IN INTEGER,
lockmode lN INTECER t
timeout tN NUMBER DEFAULT MAXWATT)
RETURN INTEGER;
FU NCTTON CONVERT( lockhandle tN VARCHAR2,
lockmode tN tNTECER,
timeout tN NUMBER DEFAULT MAXWATT)
RETURN INTECER;

CONVERT is used to.change a lock


from one mode to another. The
arguments and return varues aie
simirar to REeUEST, and are described
fotowing tabre. Like REQUEsi, coNveRT
llth.:
Irrst parameter.
is overroaded on the

Parameter TYPe Description


id INTECER User assigned lock identifier, from
O to
1073741823.

lockmode INTECER Lock mode rbquested, as defined


in
Table B_3.
timeout NUMBER Maximum number of seconds to wait
before timing out.
Appendix B: Guide to Supplied Packages 90 I

CONVERT Return Value Meaning


0 Success
1 Time-out
2 Deadlock detected
3 Parameter error
4 Don't own the lock sPecified
5 lllegal lock handle

RELEASE
FUNCTION RELEASE('d IN INTECER) RETURN INTECER;
FUNCTION RELEASE(/ockhandle lN VARCHAR2) RETURN INTECER;

This function releases a lock that was acquired by REQUEST. lt is


overloaded on the type of its argument-the lock can be specified either by
lD or by a lock handle. The return values are listed here:

RELEASE Return Value Meaning


0 Success
3 Parameter error
4 Don't own the sPecified lock
5 Invalid lock handle

SLEEP
PROCEDURE SLEEF(seconds lN NUMBER);
SLEEP suspends the current session for the specified number of
seconds. The maximum resolution is hundredths of a second, so seconds
can be fractional.

DBMS_OUTPUT
The DBMS-OUTPUT package provides limited output capability to
PVSQL, when used in conjunction with SQL*PIus or Server Manager. lt is
useful for debugging and testing your PL/sQL code' For more information'
see Chapter 14.
902 OracleS PUSQL Programming

DBMS PIPE
The DBMS_PIPE package is similar*to DBMS-ALERT, in that it allows
communication between different sessions connected to the same database.
Messages sent over pipes, however, are asynchronous. Once a message is
sent, it will go through even if the transaction that sent it rolls back. For
more information, see Chapter 16.

DBMS REFRESH & DBMS SNAPSHOT


These packages are used to manage snapshots and snapshot Sroups,
both of which require the distributed option. DBMS-REFRESH is used to
create groups of snapshots which can be refreshed together, and
DBMS-SNAPSHOT allows you to refresh a snapshot which is not
necessarily paft of a snapshot group. For more information, see the
Oracle documentation.

DBMS_RE PCAT, DBMS_REPCAT-AUTH


ANd DBMS REPCAT ADMIN
These packages are used to manage Oracle's symmetric replication facility,
which requires the replication option. DBMS-REPCAT allows you to use
the facility, while DBMS- REPCAT AUTH and DBMS REPCAT ADMIN
allow you to administer the facility. For more information, see the
Oracle documentation.

DBMS ROWID
The DBMS-ROWID package is used to convert between the OracleZ and
Oracle8 ROWID formats. For more information, see the Oracle] Server
SQL Reference.

DBMS SESSION
The ALTER SESSION command is DDL, and thus is not allowed directly in
PLISQL. The DBMS-SESSION package provides an interface to some of the
options available with ALTER SESSION, callable from PL/SQL blocks. The
DBMS-SQL package can be used as an alternative to DBMS-SESSION,
since it allows execution of arbitrary statements, inclLrding ALTER SESSION.
Appendix B: Guide to Supplied packages
903

SET_ROLE
PROCEDURE SET_ROLE (role cmd VARCHAR2);

SET-ROLE is equivalenr to the sel command sET ROLE.


The rext of
rol.e-cmd is appended to 'sET ROLE', and then the string is
executed. since
roles are disabled inside stored procedures, calling sET_ROLE
in a stored
subprogram or trigger will have no effect. rf the rol"le ,"qrir",
a password,
you include it in the call. For example, the following code
enables the role
Administrator with the password ,admin,:

DBMS SESSION.SET_ROLE(,Adrninistrator fDENTTFIED By admin,


);

sET_SQL_TRACE
PROCE D U RE SET_SeL_TRAC E(sgl_frace B OOL EAN ) ;

This procedure is used to turn SQL tracing on or off. lt is equivalent


to
ALTER sESSloN sET SeL_TRACE = sql_trac6. For more
information on
tracing, see Chapter 22.

SET NLS
PROCEDURE SET_NLS( param VARCHAR2, valueVARCHAR2);

This command is equivalent to ALTER sESSroN sET param


= value,
where param is a valid NLS parameter, and valueisthe value
to whicl-r it
should be set. This procedure is not valid in triggers. paramand
value will
be used directly in the resurting ALTER sESSloiicommand,
so if value is a
text literal it must contain the embedded single quotes. For example,
we
can change the date format with

DBMS SESSION. SET-NLS',:ii;ifiifi_i;,ffi;,.,..,,,,


),
Note the embedded single quotes in the specification of the format
string.
904 Oracte8 pUSeL programming

CLOSE_DATABASE LINK
PRocE D u R Ec L.'E-DATA BAS E-L r N K( dblink v,q RcHn nz t ;
ThiS PTOCCdUTC iS CqU|VAICNI tO ALTER SESSION CLOSE IfATABASE
LINK dblink' rt closes an impricit connection
to a remote database.

SET_LABEL
PROCEDURE SET LABEL(/b/ VARCHAR2);

This procedure is varid in Trusted oracre and


^ is equivarent to ALTER
sESSloN sET LABEL = rbr. tbtcan be'DBHrcH,, ,oeLowl
or another
text label.

SET_MLS_LABEL_FORMAT
PRocEDURE LABEL FoRMAT(fmr VARCHAR2);
'ET-MLS
Also valid in Trusted oracre, sET_MLS LABEL_FORMAT
is equivarent
to ALTER sESSroN sET MLS_LAsrL
_ronv AT = imt- tLchrnges the deiault
label format for the current ,ession.

RESET_PACKAGE
PROCEDURE RESET PACKACE;

There is no seL equivarent for RESET pACKACE.


lt will free the
memory used to store th.e package state;d deinstantiate
all packages for
the session' This is the situation lt the beginning
of a session.'

UN|QUE_SESS|ON tD
FUNCTTON UNTQUE_SESS|ON lD RETURN VARCHAR2;

This function returns a string with a maximum rength


oi 24 6ytes, which
is unique among all sessions currentry connected
,o,fr" autJur". Murtipre
Appendix B: Guide to Supplied Packages 905

cails to UNIQUE_SESSION_lD from the same session always return the


same result. There is no SQL equivalent.

IS ROLE ENABLED
FUNCTION lS ROLE ENABLED(rolenameVARCHAR2)
RETURN BOOLEAN;

This function returns TRUE if rolename is enabled for this session and
FALSE otherwise. lf lS ROLE ENABLED is cailed from a stored subprogram
or trigger, it will always return FALSE since all roles are disabled there.

DBMS SHARED POOL


The DBMS_SHARED_POOL package is used to manage the shared pool.
You can pin packages and procedures in the shared pool, so they won't get
aged out. This is a key component of a properly turred PL/SQL
environment. For more inforrnatiorr, see Chapter 22.

DBMS_SQL
eE DBMS_SQL irnplements dynamic PLISQL. Using this package, your
program can construct SQL statements and PL/SQL blocks at run
time and execute them. DBMS_SQL can also be used to execute DDL
statements from PL/SQL, which are not perrnitted otherwise. For more
information, see Chapter 15.

DBMS TRANSACTION
The DBMS TRANSACTION package provides procedures for
transaction management. Many of the commands available here are
also available in their SQL equivalents directly in PL/SQL. They are
i ncl uded for completeness.

SET TRANSACTION Commands


PROCEDURE READ ONLY;
PROCEDURE READ WRITE;
PROCEDURE USE ROLLBACK SEC\lENT(r'b_nanteVARCHAR2);
905 OracleS PUSQL Programming

These procedures are equivalent to the SQL commands SET


TRANSACTION READ ONLY, SET TRANSACTION READ WRITE, and SET
TRANSACTION USE ROLLBACK SECMENT rb name. Each must be
executed as the first statement in a transaction.

ALTER SESSION ADVISE Commands


PROCE DU RE ADVISE-COMMIT;
PROCEDURE ADVISE ROLLBACK;
PROCEDURE ADVISE NOTHINC;

These procedures are equivalent to ALTER SESSION ADVISE COMMIT,


ALTER SESSION ADVISE ROLLBACK, and ALTER SESSTON ADVTSE
NOTHINC. They are used to send advice for a distributed transaction. This
advice will be in the advice column of the dba_2pc-pending data
dictionary view in the remote database in case the transaction is in doubt.

COMMIT Commands
PROCEDURE COMMIT;
PROCEDU RE COMMIT_COMMENT(cmnt VARCHAR2);
PROCEDURE COMMIT FORCE(
xidVARCHAR2,
scn VARCHAR2 DEFAULT NULL);

These commands are equivalent to the SQL commands COMMIT,


COMMIT COMMENT cmnt, and COMMIT FORCE xid, scn. COMMIT
COMMENT and COMMIT FORCE are typically used in distributed
trinsactions.

ROLLBACK and SAVEPOINT Commands


PROCEDU RE SAVEPOI NT (savept VARCHAR2);
PROCEDURE ROLLBACK;
PROCE D U RE ROL L BAC K_SAVEPOI NT(sa vepr VARC HAR2 );
PROCEDU RE ROLLBACK_FORCE(xid VARCHAR2);
Appendix B: Guide to Supplied packages gOT

These procedures are equivalent to the sel commands


sAVEpolNT
savept, ROLLBACK, ROLLBACK To sAVEporNT savept, and
RoLLBACK
FORCE xid. xid is the local or global transaction lD. RbLLBACK
FoRCE is
typically used in distributed transactions.

B EG I N_D I SC RETE_TRANSACTION

PROCEDURE BECIN DISCRETE TRANSACTION;

This procedure is used to mark the current transaction as discrete.


.
discrete transaction can run faster than a regular transaction,
A
because no
undo information is written. Ail changes toihe database are buffered
and
actually applied at CoMMlr time. There are a number of restrictions
on
discrete transactions, and they shourd be used with care. For
more
information, see the oracle server Application Developer,s
cuide.

PURGE_MIXED
PROCE D U RE PU RCE_M tXED(xid VARCHAR2);

This procedure can be used to purge mixed transactions,


which are
distributed transactions in which somJsites have committed
and others
rolled back. tt should be used with care by the DBA or appiication.
xid
should be set to the transaction lD as stored in the local_tran
id coiumn in
dba_2pc_pending.

LOCAL_TRANSACTION ID
FUNCTION LOCAL TRANSACTION-ID(
create_transact i o n BOOLEAN DEFAU LT FALSE)
RETURN VARCHAR];

This function retLrrrs .r unique icrentifier for the current transaction


or
NULL if there is no crttrent transaction. The identifier is unique
to the local
instatrce. li create_trarts.tt-lion is TRUE, a transaction is created
if it does not
already exist.
908 OracteS pUSeL programming

STEP ID
FUNCTION step_id RETURN NUMBER;

This function returns a unique positive integer that


orders the DML
operations of the current transaction. The valuJ returned
is unique with
respect to the current transaction only.

DBMS_UTILITY
The DBMS-urLrry package provides additionar
functionarity for
managing procedures, reporting errors, and other information.

COMPILE-SCHEMA
PROCEDURE COMptLE SCHEMA(schema VARCHAR2);

. This procedure will comp.ire ail procedures, functions, and packages in


the specified schema, equivarent to the sel commands
ALtrR
PROCEDURE coMprLE, ALTER FUNCTTON
coMprLE, or RrteR
PACKACE coMPrLE. rf you don't have ALTER privireges
fo.. one or more
objects in schema, an ORA-20000 error is raised.

ANALYZE_SCHEMA
PROCEDURE ANALYZE SCHEMA(
schema VARCHAR2,
method VARCHAR2,
esti mate_rows N UMBER DEFAULT N U LL,
esti mate_percenr N UMBER DEFAULT NU LL);

This procedure will anaryze ail the tabres, crusters,


. and indexes
- in the
schema. The parameters are defined by the following
tabb.
Appendix B: Guide to Supplied Packages 909

Parameter Type Description


schema VARCHAR2 Schema whose objects should
be analyzed.
method VARCHAR2 Analyze method----either NULL or
ESTIMATE. lf ESTIMATE, then one of
est i m ate_rows or e sti m ate_pe r ce nt
should be non-zero.
estimate rows NUMBER Number of rows to estimate.
estimate_percent NUMBER Percentage of rows to estimate. lf
estimate_rows is specified, this
parameter is ignored.

FORMAT_ERROR_STACK
F U NCTI ON FORMAT-E RROR_STACK RETU R N VARC HAR2;

This function will return the entire error


stack, with a maximum length
of 2000 bytes. lt is useful in exception handlers.

FORMAT_CALL_STACK
FUNCTION FORMAT CALL STACK RETURN VARCHAR2;

This function returns a string consisting of the current call stack-all


of the procedures that are currently executing. The maxintum length is
2000 bytes.

IS_PARALLEL_SERVER
FUNCTION IS-PARALLEL-SERVER RETURN BOOLEAN;

This function returns TRUE if the instance is running in parallel server


mode and FALSE otherwise.
910 Oracle8 PUSQL Programming

GET TIME
FUNCTION CET TIME RETURN NUMBER;

Returns elapsed time in hundredths of a second. This is useful for timing


a procedure. For example:

DECLARE
v-SIart NUMBER;
v_End NUMBER;
BEGIN
V STATT := DBMS UT'ILITY.GET -TIME;
/* Do some work here */
v End := DBMS UTILfTY.GET TIME;
/* The work took (v_Start - v_End) * 100 seconds to execute. */
END;

NAME RESOLVE
PROCEDURE NAME RESOLVE(
NAMC IN VARCHAR2,
context lN NUMBER,
schema OUT VARCHAR2,
partl OUr VARCHAR2,
paft2 OUr VARCHAR2,
dblink OUT VARCHAR2,
parrl_type OUT NUMBER,
obj ect_nu mber OUf N UMB ER);

NAME_RESOLVE is used to resolve a given reference into its


components. C iven i nput of "example, Debug. Reset@dbl i nk", for example,
the output will be separated into 'example', 'Debug', 'Reset', and 'dblink',
and returned in schema, partl , part2, and dblink, respectively. The
parameters are described in the following table.

Parameter Datatype Description


name VARCHAR2 Name of the object to resolve.
context NUMBER Reserved for future use-must be
passed as 1.
Appendix B: Guide to Supplied Packages 9I I

Parameter Datatype Description


schema VARCHAR2 Schema of the object, if specified
as part of name.
partl VARCHAR2 First part of the name. This would
be the package name if the object
is a packaged procedure. lf it is
not a packaged procedure, this is
the entire name. This is also
determined by partl _type.
parl2 VARCHAR2 Second part of the name, if
applicable.
dblink VARCHAR2 Database link name, if applicable.
partl _type NUMBER Determines the meaning of part1.
Valid values are
5 - synonym
7 - procedure
B - function
9 - package
object_number NUMBER lf the object was successfully
resolved, this is the object number
as recorded in the data dictionary.

PORT STRING
FUNCTION PORT STRINC RETURN VARCHAR2;

This function returns a string that uniquely identifies both the version of
Oracle and the operating system. The maximum length is dependent on the
operating system.

UTL FILE
The UTL-FILE procedure implements file l/O in PLISQL. Using this
iltd'.Tlil package, PL/SQL programs can read from and write to operating
system files located on the server. The accessible files and directories are
limited by parameters in the INIT.ORA database initialization file, for
security. For more information, see Chapter 18.
914 Oraete8 pUSeL programming

ACCESS-INTO NULL Assignment Blocks


Exception
COLLECTION IS NULL Collections Comments
Exception
COMMIT Statement Conditions Cursor Variables
CURSOR ALREADY Cursors Datatypes
OPEN Exception
DDL DELETE Statement DML
DUP-VAL-ON-INDEX EXCEPTION_lNtT Pragma Exceptions
Exception
EXIT Statement Expressions External procedures
extproc FETCH Statement %FOUND Aftribute
Functions COTO Statement tlo
ldentifiers lF Statement INSERT Statement
INVALID CURSOR INVALID NUMBER %ISOPEN
Exception Exception
Literals LOBs LOCK TABLE Starement
LOGIN DENIED Loops MAP and ORDER rnethods
Exception
Nested Tables NO-DATA-FOUND NOT_LOGCED ON
Exception Exception
%NOTFOUND NULL Statement NULL Value
OPEN Statement Packages Procedural Statements
Procedures PROCRAM ERROR RAISE Statement
Exception

TABLE C- 1. pL/seL Features


Appendix C: Glossary of PUSQL Features 9 I 5

Records RESTRICT REFERENCES RETURN Statement


Pragma
ROLLBACKStatement %ROWCOUNTAttribute %ROWTYPEAttribute
ROWTYPE MISMATCH SAVEPO|NTStatement SELECT..lNTOStatement
Exception
SET TRANSACTION SQL Cursor SQL Statements
Statement
Function
SQLCODE SQLERRMFunction STANDARD Package
Statements STORAGEERROR SUBSCRIPT BEYOND
Exception COUNT Exception
SUBSCRIPT OUTSIDE Tables TIMEOUT ON RESOURCE
LIMIT Exception ' Exception
TOO_MANY_ROWS TRANSACTION_BACKED_ Triggers
Exception OUT Exception
%fYPE Attribute UPDATE Statement VALUE_ERROR Exception
Variables and Constants VARRAYs ZERO DIVIDE Exception

TABLE C- 1. PL/SQL Features (Continued)

ACCESS-INTO-NULL Exception This predefined exception


corresponds to the Oracle error I'ORA-6530: Reference to
uninitialized composite". lt is raised when you try to access an attribute
or method of an object reference which is NULL. For more information,
see Chapter 11.

Assignment Assignment statements are used to place a value into a


PL/SQL variable. The syntax is

vari able := expression;

where variable is an identifier for a PL/SQL variable, and expressionis a


PL/SQL expression. expression is considered to be an rvalue and variable
9|5 OracteS pUSeL programming

an lvalue. lf expression and variable are not of the


same type, pLlSeL will
attempt to convert the type of expression to the
type of variabre. rf the
conversion fails, an error is raised. For more information,
see Chapter 2.

Blocks All pLlSeL programs are made up of blocks. A pLlSeL


block
consists of decrarative, executabre, and exception-handring
,".iionr. ihu
syntax for a block is

DECLARE
declarative section here
-
BECIN
executable section here
-
EXCEPTION
exception_handling section here
-
END;

The DECLARE, BECTN, EXCEproN, and END keywords


derimit the
sections' only the executable section is required. For
more information, see
Chapter 2.

ffi ffi .'"?:,'rff Ji:"T^-j'"*i::"=;:,:dffi i,lii'J#?:l'::dexception


uninitialized collection". lt is raised when you try to
add an element to, or
modify an element in, a nested tabre or varray coilection
type. For more
information, see Chapter j2.

Collections A collection is a group of pLlSeL variables which can


be
manipulated either individually, or as a unit. pLlSeL
version 2 has only one
collection type-the pllsel tabre. pllsel uurrion s.o
aaas nested tabres
.and varrays to the set of collection types. For more information, see
Chapters 3 and'12.

comments Comments are used to document your code and make


it
more readable. The pllsel compirer ignores them. There
are two types of
Appendix C: Glossary of PUSQL Features 917

comments: single line and multiline or C-style. Single-line comments start


with two dashes (--) and continue to the end of the line (delimited by a
newline character). Multiline comments start with /* and end with */. See
Chapter 2 for more information. For example:

-- This is a single l-ine comnent.


/* This is a multiline
comnent, continued over two fines. */

COMMIT Statement The COMMIT SQL sratement is used to end a


transaction and make all changes permanent. Until a transaction is
committed, other users cannot see the changes made to the database by the
transaction. COMMIT also releases any locks acquired by the transaction.
The syntax is

coMMrT [woRK];

where the WORK keyword is optional. For more information, see Chapter 4.

Conditions A condition is an expression which evaluates to a


BOOLEAN value. Conditions are used in lF..THEN, EXIT..WHEN,
WHILE..LOOP, and the WHERE clause of SQL statements. Conditions can
be combined using the logical operators AND, OR, and NOT. They can be
construtr,ted using logical operators such as =, )=, LIKE, lN, and BETWEEN.
For more information, see Chapter 2.

CITRSOR ALREADY OPEN Exception This predefined exception


corresponds to "ORA-6511: PVSQ!: cursor already open.,' lt is raised when
you try to open a cursor that is already open. Yo-u can determine the open
status of a cursor with the %ISOPEN attribute. For more information about
cursors, see Chapter 6.

Cursors Cursors are used to control the processing for queries that
return more than one row. A cursor is declared using the CURSOR..IS
syntax, then processed with OPEN, FETCH, and CLOSE. Cursor attributes
are used to determine the current status of a cursor, with information about
how many rows the cursor has returned, whether the cursor is open, and
whether the last fetch was successful. For more information, see Chapter 6.
918 OracleS PUSQL programming

cursor variables Cursor variabres are dyrramic cursors. A given


cursor variable can be opened for different queries using the opEN..
FoR syntax. Typically, a cursor variabre is opened on the serJer and
fetched from and then closed on the client. Cursor variables are
available in
PLlsQL 2,.! and higher. with release 2.2, you must use a client program
such as sQL*Plus, or one r,r,ritten using the precompilers or oCl, to access
cursor variables. PLlsQL 2.3 can process cursor uaii"bles entirely on
the
server. A cursor variable is declared with type REF cuRSOR and is
the only
pointer type available in PLlseL up to rereas e 2.3. For more information,
see the section "Cursor Variables,, in Chapter 6.

Datatypes PLlsQL supports all of the datatypes provided by the oracle


server, plus a number of additional ones. The types are described in
detail
in Chapter 2, and listed below by category and iamily. Entries in the
table
with a * are available only in pLlSeL g.O and higher.

Category Family Types


Reference Types N/A REF CURSOR, REF object typex
Composite Types N/A RECORD, TABLE, VARRAy*
LOB Types+ BFILE, LOB, CLOB, NLOB
ScalarTypes Numeric BINARY_|NTECER, DEC, DECIMAL,
DOUBLE PRECISION, FLOAT, INT,
INTEGER, NATURAL, NATURALN*,
NUMBER, NUMERIC, PLS-INTECER,
POSITIVE, POSITIVEN*, REAL,
SICNTYPE*, SMALLINT
Boolean BOOLEAN
Trusted MLSLABEL
Character CHAR, CHARACTER, LONC,
NCHAR*, NVARCHAR2*, STRINC,
VARCHAR, VARCHAI{2
Raw RAW, LONC RAW
Date DATE
Rowid ROWID
Appendix C: Glossary of PUSQL Features 919

DDL (Data Definition Language) DDL statements modify data


dictionary objects, rather than the data contained in them. They include
CREAIE TABLE and DROP PROCEDURE, for example. pLlSeL does not
allow DDL statements to be used directly, because the compiler is
implemented using early binding. PL/SQL 2.1, however, allows the use of
DDL statements with the DBMS_SQL package. This package allows
statements to be constructed at runtime, rather than compile time. For more
information, see Chapter 15.

DELETE Statement The DELETE SQL statement is used to remove


rows from a table. lt is defined with

DELETE [FROM] table laliasl


WHERE where clause I CURRENT OF cursor,

Table specifies the table from which the rows should be deleted. An alias
for the table name can also be specified if desired. rhe where clause
determines which rows will be deleted. lf the CURRENT.oF cursor clause
is used, then the last row fetched trom cursorwill be deleted. After a delete
that removes one or more rows, SQL%NOTFOUND is FALSE, SeL%FOUND
is TRUE, and sQl%RowcouNT contains the number of rows deleted. rf
the wherejclause does not match any rows, no rows are deleted and
SQL%NOTFOUND is TRUE, SQL%FOUND is FALSE, and
SQL%ROWCOUNT equals 0. For more information, see Chapter 4.

DML (Data Manipulation Language) DML statements (SELECT,


UPDATE, DELETE, INSERT, EXPLAIN PLAN) modifi, the data in Oracle
objects, rather than the objects themselves. DML statements can be
included directly in PLISQL. For more information, see Chapter 4.

DUP_VAL_ON_INDEX Exception This predefined exception


corresponds to the oracle error "oRA-1: unique constraint violated". lt is
raised when you try to insert a row into a table with a unique index defined
for a particular field, and the value for the field you are trying to insert
already exists in the table.
920 OracteS pUSeL programming

ExcEprroN rNrr pragma pragma


EXCEptoN_rNrr is used to
associate a named exception with an-oracre
error. ThI provides named
exceptions in addition to the predefined ones.
The syntax is

PRACMA EXCEpTI ON_l N lT(excep ti o n_n a me, e r ror_n u m be r) ;

where exception_nulT.,r_1n exception currently


in scope, and
error number is the seLCoDE uuire .orr"sponding
to an oracre error. For
example, the following code will raise e NonExist""ntrubl"
whenever the-
error "ORA-942: Iable or view does not exist,, is
returned:
DECLARE
e_NonExistentTabfe EXCEpTION;
EXCEPTTON-TNIr (e-NonExistentrable,
-942) ;
:T"*

For more information, see Chapter I O.

Exceptions Exceptions are used to trap runtime errors. When


an error
occurs, an exception is raised, and contror immediatery
passes to the
exception-handling section of the block. rf there
rs no exception_handling
section in the current brock, the exception is propagated
out to the
enclosing block. predefined exceptions are defined
in the sTANDARD
ga;kage, and you can define yorr o*n exceptions as weil. For more
information, see Chapter 10.

Exlr statement EXrr is used to pass contror out of a currentry


executing loop. lt is defined with

EXIT [loop_name] IWHEN condition];

where condition is a,boo.rean expression. rf there is


no WHEN crause, the
loop is exited immed.iatery. rf there is a WHEN crause,
the roop is exited
only if condition evaluates to TRUE. rf specified, tioi_nu."should
march
a label at the beginning of a roop. For more informaiion,
see Chapter 2.

Expressions An expression is a combination of variabres, constants,


literals, operators, other expressions, and function
cails. An expression
Appendix C: Glossary of PUSQL Features 921

evaluates to an rvalue. Expressions can be used in a variety of PL/SQL


statements, including the WHERE clause of SELECT, UPDATE, and DELETE
statements. Expressions are combined using operators such as +, -, NOT,
OR, ll, and -. lf an expression is composed of items that have different
types, they are converted to the same type first, and then the operators are
applied. For more information, see Chapter 2.

External Procedures External procedures are a new Oracle8


ieature which allows you to write a procedure orfunction in C
and call it directly from PL/SQL. Doing this requires a wrapper function in
PLISQL, which is created with the CREATE IOR REPLACEI PROCEDURE ...
AS EXTERNAL statement. You must also specify the mapping between the
PL/SQL and C datatypes in the CREATE statement. For more information,
see Chapter 20.

extproc External procedures are called by a special Oracle


process known as extproc. Extproc is started the first time a session
makes a callto an external procedure, and remains active for the duration
of that session. Extproc loads the shared library containing the external
procedure, and then calls it. lt communicates with the original shadow
process with SQL*Net. For more information, see Chapter 20.

FETCH Statement FETCH is used to retrieve rows from a cursor or


cursor variable into PL/SQL variables or a PL/SQL record. lt is defined with

FETCH cursor I cursor variable


INTO record I list_of_variables;

where cursor is the name of a previously opened cursor, or cursor_variable


is the name of a previously opened cursor variable (PL/SQL 2.2 and higher).
The /isf of variables or the fields in record should match the select list of
the query. Typically, FETCH is called in a loop whose exit condition is
determined by the %NOTFOUND attribute. Each call to FETCH will
retrieve one more row ahd increment cursor %ROWCOUNT by one. For
more information, see Chapter 6.
922 OracteS pL/SeL programming

%FouND Attribute This boolean cursor attribute is used to


determine
whether the last FETCH for a cursor or cursor variable (pLlSeL
2.2 and
higher) rerurned a row. lt is defined with

cursor %FOUND I cursor variable"hFOtJND

where cursor is the name of a cursor, and cursor_variableis


the name of a
cursor variable. lf the last FETCH returned a row, then
%FouND evaluates
to TRUE. After a cursor is opened, but before the first FETCH,
%FouND
evaluates to NULL. y"FouND is the opposite of the
%NorFouND cursor
attribute. For more information, see Chapter 6.

Functions Functions are named pl/sel blocks that return a value and
can be called with arguments. They can be used as part
oian expression.
legal in prccedural statements, and certain functions
Ih:L1r"
in sQL statements in PL/seL 2.r and higher. Functions
can be used
."n b" stored in the
database with the CREATE tOR REPLAC:I FUNCTION
.ornr.n.J, or they
can be located in the declarative sec:ion of another block.
For more
information, see Chapter Z.

Goro statement coro passes contror to a statement identified by a


label. The syntax is

COTO label;

where labelis delimited by doubre angle brackets << and >>.


lt is illegal to
branch into or out of an exception haniler, or into an rF statement,
loop, or
sub-block. For more information, see Chapter 2.

for inpuVoutput directly in the

":#5r,il:3dJli :?f ,llfi ;1"'""'


s itu at i o n w i rh the u rL- FrL E pac kase, -'i;#l?S"i ii ;iJlr"3l?$^i,
ourPUT is discussed in chapter f 4, and urL_FrLE in Chapter 18. -
ldentifiers The name of any plisel object is an identifier. rdenrifiers
are not case-sensitive, and consist of up to 30 characters
in the pl/sel
Appendix C: Glossary of PUSQL Features 923

character set. ldentifiers must begin with a letter. For more information,
see Chapter 2.

lF Statement The lF statement is used to conditionally execute a


sequence of statements. lt is defined with

lF conditionl THEN
sequ ence_of_statements 1 ;

[ELSIF condition2THEN
s eq uence ate m e n t s 2 ;)
-of -st
IELSE
se q u e n c e_of_state m e n ts 3 ;]
END IF;

The sequence-of-statements under the first condition that evaluates to


TRUE is executed. At most, one sequence of statements will be executed.
For more information, see Chapter 2.

INSERT Statement INSERT is used to add a row to a table. lt is


defined with

INSERT lNTo table l(column_list))


VALU ES (expressi on-l i st) ;

where tableis a reference to the table into which the rows will be insefted,
and expression-list is a comma-separated list of expressions that make up
the fields of the new row. lf column /ist is specified, then it determines the
columns that will have values. Columns that are not specified will have a
value of NULL. lf column-list is not specified, then expression-list should
correspond to all the columns in table. For more information, see Chapter 4.

INVALID-CURSOR Exception This predefined exception corresponds


to the Oracle error "ORA-1001: invalid cursor". lt is raised when a cursor is
invalid but you try to use it regardless. This can occur if you try to fetch
from a cursor before it has been opened, or if you fetch from a cursor
declared for update after a commit. For more information on cursor
processing, see Chapter 6.
924 OracteS pUSeL programming

lNvALrD NUMBER Exception This predefined exception


corresponds
to the oracre error "oRA- 1722: invarid number,'.
rt is raised when an
attempted conversion to a NUMBER varue
faired. For exampre, the string
'Nineteen Hundred and Ninety Five, cannot
be converted into a NUMBER
since it does not contain onry digits, a decimar
point, o,. an optionar sign.
For more information on numbei conversions,
see chapte rs 2 and 4.

lsoPEN The %lsoPEN cursor attribute is used to determine whether


a
cursor or cursor variabre (pLlsQL 2.2 and higher)
is open. rt is defined with

cLtrsor %lSOPEN I cursor variableo/olSopEN

where cursor is the name of a


name of a cursor variable. lf t
with the OPEN or OpEN..FOR star
%lSOPEN will return TRUE. SeL%l
implicit cursor is arways crosed after execution
more information, see Chapter 6.
of the sel statement. For

Literals Literars can be crassified as either numeric or


character. A
numeric literar.is composed of the digits 0 through
9, with an optionar sign
andlor decimal point' Numeric literais can also
8e specified i" i.i""lii."'
notation' All numeric literals have datatype NUMBER.
A character literal is"
any sequence of characters enclosed in single
quotes. A double_qro*.t-
string is nottreated as a literal, but as a case-sensitive
identifier. Character
literals have datatype CHAR, not VARCHAR2.
For more information,
see Chapter 2.

ffi .#ilriJ:#iLR':.ji?8fi '",iiffi ?"lfi fll;?:fi i,io"


"'"?ff using
manipulated either the pLlSeL DBMS_LOB pn.kug", or an
OCI
interface. A LoB can sto.re up to 4 gigabyte.r.nuru.t"lor
.more information, see Chapter 21
binary dltu. ro,.
.

LocK TABLE statement LocK TABLE is a DML statement


that can
be used to lock an entire table. The SELECT..FoR
uPDATE statement is
used to lock selected rows within a table. The
syntax forLOCK TABLE is
Appendix C: Glossary of PUSQL Features 925

LOCI(TABLE tablelN /ock mode [NOWAI-T];

where tableis a reference to the desired table, and lock_mode specifies the
mode. Available modes include ROW EXCLUSIVE, ROW SHARE, SHARE
UPDATE, SHARE, SHARE ROW EXCLUSIVE, and EXCLUSIVE. lf NOWAIT
is specified, the statement will return immediately either with the lock
acquired or with TIMEOUT_ON RESOURCE raised if the lock cannot be
acquired. lf NOWAIT is not speciiied, then the LOCK TABLE will wait
until the lock can be acquired. For more information, see the Oracle Server
SQL Reference.

Loops There are four different kinds of looping structures in PLISQL.


Basic loops are delimited with the LOOP and END LOOP keywords.
WHILE loops start with the WHILE..LOOP keywords and end with END
LOOP. Numeric and cursor FOR loops use the FOR index IN..LOOP and
END LOOP keywords. All loops can optionally begin with a label, which
can be used in the EXIT statement within the loop, if desired. For more
information on simple, WHILE, and numeric FOR loops, see Chapter 2.
For more information on cursor FOR loops, see Chapter 6.

LOGIN_DENIED Exception This predefined exception corresponds to


the Oracle error "ORA-1017: invalid username/password; logon denied". lt
is raised when an incorrect user name/password combination is specified.

MAP and ORDER Methods MAP and ORDER methods are


special methods for object types, which are used to determine
how to sort instances of an object type. A given object type can have
either a MAP or an ORDER method, but not both. For more information,
see Chapterl2.

NOT-LOGGED-ON Exception This predefined exception


corresponds to the Oracle error "ORA-101 2: not connected to Oracle". lt
is raised if an SQL statement is issued before a valid connection has been
establ i shed.

%NOTFOUND The %NOTFOUND cursor attribute is used to determine


whether the last FETCH from a cursor or cursor variable (PL/SQL 2.2 and
higher) did not return a rew. lt is defined with
926 OracleS PUSQL programming

cursofloNOTFOUND I cursor_variable%NOTFOUND

Nested Tables Nested tables extend the pLlSeL table functions


available in versior-r 2. Unlike version 2 pL/soL tables. a nesred

SELECT..INTO, see Chapter 4. Ftor more information on pL/SeL


tables, see
Chapter 3.

NULL Statement The NULL statement, specified with

NULL;

performs no work. lt is useful for indicating that no action is


to be taken at a
point where PL/SQL syntax demancls a statement. For more
intbrmation, see
Chapter 2.
Appendix C: Glossary of PUSQL Features 927

OPEN Statement The OPEN staternent is used to open a cursor (or


cursor variable, in release 2.2 and higher). When a cursor is opened, any
binclvariables in the WHERE clause are evaluated, and the active set is
deterrnined. The bind variables will not be examined, nor willthe active
set charrge unless the cursor is closed and then reopened. The syntax for
OPEN is

OPEN cursor nane; I OPEN cursor-variabie FOR select-statement;

where cursor_name specifies a prevrously defined static cursor, and cursor-


variable specifies a previously defined cursor variable. For a cursor variable,
the query is specified with se/ect statenent. For more intormation, see
Chapter 6.

Packages Packages are defined as two separate data clictionary objects-


the package header (or specification) and the package body. The heacler is
created with the CREATE OR REPLACE PACKACE command;the body with
the CREATE OR REPLACE PACKACE BODY command. Packages must be
stored in the database; they cannot be placed in a declarative section like
procedures and functions. Packages themselves can contain procedures,
functions, variables, types, cursors, and exceptions. ltems declared in the
package header will be visible outside the package, while items defined
only in the package body will be private to the package. Packages also
break the dependency chain because the package body can be recompiled
without affecting the package specification. For more information, see
Chapter B.

Procedural Statements Procedural statements, as opposed to SQL


statements, control the processing of a PL/SQL block. They are processed
by the PL/SQL engine and are not sent to the SQL statement executor in the
database. Procedural statements include calls to procedures, assignments,
conditional control statements such as lF..THEN, and loops. For more
information, see Chapter 2.

Procedures Procedures can be stored in the database with the CREATE


OR REPLACE PROCEDURE statement, or they can be declared in the
declarative section of a block. A procedure is a named block that can be
928 Oracle8 PUSQ!- Programrning

called with parameters. The parameters can either accept a value from the
calling environment (lN), return a value to the calling environment (OUT),
or both (lN OUT). For more information, see Chapter Z.

PROGRAM-ERROR Exception This predefined exception corresponds


to the Oracle error " PL/SQI-: internal ercor mmm, arguments [mmm],
lmmml, Immm], lmmml, lmmml, lmmmf", where mmm represents the
code and arguments associated with this particular internal error. This error
is raised when an internal PL/SQL error has occurred, which should not
normally occur.

RAISE Statement RAISE is used to signal that an error has occurred by


raising an exception. The exception can be user defined or predefined. The
syntax for RAISE is

RAISE lexception_namel;

where exception-name spOcifies the exception to be raised. The only place


where it is legal to issue a RAISE statement without a named exception is ill
an exception handler. ln this case, the current exception is raised again. For
more information, see Chapter 10.

Records PL/SQL records are used to group logically related information


of different types. Like PL/SQL tables, you must first define a record type
and then declare a variable of that type. For example, the following
declarative section declares a record to hold some of the student
information:

DECLARE
TYPE t_StudentT\@e rS RECORD (

FirstName students. first nametTypE;


LastName students.last nametTypE;
TD students . fDtTYPE) ;
v_Studentf nf o t_StudentTg)e ;

The %ROWTYPE attribute returns a PVSQL record as well. For more


information, see Chapter 3.

RESTRICT_REFERENCES Pragma The RESTRTCT_RE FERENCES


pragma is used to assert the purity level for user-defined functions
Appendix C: Glossary of PUSQL Features 929

and methods. ln order to be used in SQL statements, you must guarantee to


the PL/SQL engine that the function does not modify any database or
package state. The pragma is specified with

PRACMA RESTRICT REFERENCES(function name,


IRNDSI [,WNDS] [,RNPS] [,WNPS]);

where function name is the function whose purity yoLt are asserting. The
purity levels, defined in the following table, can be specified in any order.
For more information, see Chapter B.

Purity
Level Meaning
RNDS Reads no database state
WNDS Writes no database state
RNPS Reacls no package state
WNPS V\ir"ites no package state

RETURN statement RETURN can be used in two ways:'to return from


a function or fi"om a procedure. lt is specified lvith

RETU RN lretu rn_v'a I uel ;

RETURN causes control to pass from a furrction or procedure back to the


calling environment. The return_value must be specified for a function, and
not for a procedure. RETURN is optional for procedures, but it is required
for functions, since a function must pass a value back to the calling
environnrent. For nrore inforntatiorr, see Chapter 7.

ROLLBACK Statement The ROLLBACK statenrent is used to end a


transaction and undr.r tlre rvork done bv th.rt transaction. lt is as if the
transaction was never [rt-qrrrr. Tlre s1'nt.rx is

ROLLBACK [WORKI ITO SAVEPOINT savepoint];

The WoRK keyword is option.rl. Like CoNlMlr, ROLLBACK also rele.rses


any locks acquired by tlre transaction. lf a savepoint is specified, only
930 OracleS PUSQL Programming

the work done after savepoint is rolled back. For more information, see
Chapter 4.

%ROWCOUNT Attribute This cursor attribute returns the number of


rows fetched so far for an explicit cursor, and the number of rows affected
by the last statement for the implicit SQL cursor. Each explicit FETCH for a
cursor will increment its %RowcoUNT value by one. For more
information, see Chapter 6.

%RowrYPE Attribute The %RowrypE attribure can be applied to a


database table. lt will return the type of a pLlSeL record consisting of all
the columns in the table, in the order in which they were specifieJ at table
creation. For example, the following declare section declares a record that
can hold a row in the classes table:

DECLARE
v_ClassInf o cf asses%ROWTypE ;

For more information, see Chapter 2.

ROWTYPE_MISMATCH Exception This predefined exception


corresponds to the Oracle error "ORA -65O4: pL/SeL: return types of
result set variables or query do not match". This error is raised when you
open a cursor variable for a difi'erent type of query than it was defined for,
using the OPEN..FOR syntax. For more information, see Chapter 6.

sAvEPolNT statement SAVEPOINT is used ro mark the place in a


transaction. The syntax is

SAVEPOI NT savepoi nt_name;

where savepoint_namei fined. Once


the savepoint is defined, LLBACK TO
SAVEPOINT command.

sELEcr..lNTo Statement SELECT..lNTo is used to retrieve one row


from the database. The syntax is
Appendix C: Glossary of pUSeL Features 93 I

SELECT select list


INTO variable listl record
FROM rable
IWHERE where_clause]
ICROUP BY group_clause]
IORDER BY order_cl ausel
IHAVI NC hav i ng_c I ause] ;

The variables in variable list should match the items in select_lisf or the
fields in rhe record should match. The row will be retrieved from the table
identified by table. The rest of the clauses determine which row will be
retrieved. lf the query returns more than one row, use an explicit cursor. lf
the query does not return any rows, the No_DATA_FouND exception is
raised. For more information, see Chapter 4.

sET TRANsAcrloN statement sET TRANSACT|ON is used to


determine the properties of the transaction. lt must be called as the first
statement in the transaction. The syntax for SET TRANSACTIoN is

SET TRANSACTION
USE ROLLBACK SECMENT segmenf I READ ONLy;

SET TRANSACTION can be used both to assign a particular rollback


segment to the transaction and to allow only read operations (queries and
LOCK TABLE statements). All queries in a read-only transaction will be
read consistently from the beginning of the transaction, rather than for each
statement. For more information, see the oracle server sel Reference.

ffi :-Y'"r',:"1':"',-,":ffi i,3al,""YilTff t["-l.rli:',x;:*1il*


beyond count". lt is raised when you reference a collection with a subscript
value that Breater than the count for a varray, or too large for a nested tabie.
For more information, see Chapter 12.

SUBSCRIPT_OUTSIDE_LIMtT Exception This predefined


exception corresponds to the oracle error "oRA-6s32: subscript
outside of lirnit". tt is raised wherr you reference a collection with a
932 OracleS PUSQL Programming

subscript value greater than the limit for avarrayt or non-positive for a
varray or nested table. For more information, see Chapter 12.

sQL cursor All sQL statements are processed in a cursor. Expricit


cursors are used for multirow queries, and they are processed using the
OPEN, FETCH, and CLOSE commands. For other SQL statements, an
implicit cursor is used. This cursor is known as the seL cursor. The four
cursor aftributes are available, and are referenced with SeL%FOUND,
SQL%NOTFOIJND, SQL%ROWCOUNT, and SeL%tSOpEN. SeL%tSOPEN
will always return FALSE since the implicit cursor is opened, the staternent
is executed within it, and the cursor is closed before %rsopEN can be
checked. For more information, see Chapter 6.

sQL Statements sQL statements, as opposed to procedural statements,

see Chapter 4.

SQLCODE Function SQLCODE is used to return the error code


associated with the current error. lt is typically used in a wHEN OTHERS
handler to determine which oracle error raised the exception. seLCoDE
returns an INTECER value. For more information, see Chapter 10.

SQLERRM Function SQLERRM returns the error message text


associated with an Oracle error code. lf no error code is specified,
SQLERRM returns the error message text for the current error. Typically,
SQLERRM is used along with SQLCODE in a WHEN OTHERS handler to
determine the text of the error that raised the exception. The maximum
length of an error message is 512 characters. For more information,
see Chapter 10.

STANDARD Package The predefined exceprions (such as


NO DATA_FOUND or INVALID CURSOR), types (such as NUMBER
or DATE), and functions (such as TO_CHAR or ADD_MONTHS) are all
defined in a PL/SQL package known as STANDARD. lt is owned by the
database user sYS and is created when the data dictionary is created by
the catproc.sqlscript. EXECUTE permission on STANDARD is granted to
Appendix C: Glossary of PUSQL Features 933

PUBLIC by catproc.sql as well. Unlike other PL/SQL packages, you can


refer to objects within STANDARD without prefixing them with the
package name.

Statements There are two kinds of statements: procedural and SQL.


Procedural statements consist of assignments, procedure calls, loops, or lF
statements, for example. SQL statements can be divided into DML (data
man ipulation language), DDL (data definition ianguage), transaction
control, session control, and system control statements. For more
information, see Chapters 2 and 4.

STORAGE-ERROR Exception This predefined exception corresponds


to the Oracle error "ORA-6500: PL/SQL: storage error". This error is raised
when PL/SQL cannot allocate enough memory to continue. lt is an internal
error, which should not normally occur.

Tables PL/SQL tables are syntactically treated much like arrays in other
third-generation languages. To declare a PL/SQL table, first you define a
new table type and then a variable of that type. For example, the following
declarative section defines a table of DATEs:

DECLARE
TYPE t DateTable TS TABLE OF DATE
INDEX BY BINAR.Y-INTEGER;
v_Dates t_DateTable;

Although a table is treated syntactically like an array, iI is not implernented


like an array. For more information, see Chapter 3.

TIMEOUT ON RESOURCE Exception This predefined exception


corresponds to the Oracle error "ORA-51: timeout occurred while waiting
for resource". lt can be raised if you specify the NOWAIT clause in a
SELECT..FOR UPDATE statement, and another session already has a lock
on the requested rows.

TOO_MANY_ROWS Exception Tlris predefined exception


corresponds to the Oracle error "Oracle 1422: exact fetch returns more
than requested number of rows". lt is raised if a SELECT..INTO statement
matches more than one row. ln this case, a cursor should be used to
retrieve the entire active set. For more information, see Chapter 6.
934 Oracte8 pUSeL programming

DECLARE
v_Fi-rstName students . f irs t_name%TypE ;
v_Currentcredits students . current_credits?TypE;

UPDATE statement The UpDATE statement is used to modify existing


rows in a database table. The syntax is

UPDATE table SEf columnl = valuel , column2 value2, ...


=
IWHERE where_clause];

where table is a reference to the table to be


lause
specifies the rows to change. The columns s
column2, and so on, wilIbe set to their corr
Appendix C: Glossary of PUSeL Features 935

UPDATE statement affects one or more rows, SeL%FOUND will be


TRUE, SQL%NOTFOUND will be FALSE, and SeL%ROWCOUNT will
contain the number of rows modified after the statement executes. lf the
statement does not match any rows, SQL%FOUND will be FALSE,
SQL%NOTFOUND will be TRUE, and SeL%ROWCOUNT will be
zero. For more information, see Chapter 4.

VALUE-ERRoR Exception This predefined exception corresponds


to the Oracle error "ORA-65O2: numeric or value error". lt is raised
if an attempted conversion of a character value to a NUMBER fails.
VALUE_ERROR is generally raised for a procedural statement; for a
sQL statement, an error such as INVALID NUMBER is raised instead.
For more information on datatype conversion, see Chapters 2 and 4.

variables and constants Variables and constants are defined in the


declarative section of a PL/SQL block. A declaration looks like

variable_name type [CONSTANT] [NOT NULL] l:= initial_valuel;

where variable nameis the name of the new variable or constant, and
type is its type. type can be either a predefined type, such as DATE or
ROWID, or a user-defined type. lf CONSTANT is specified, the value of
the variable cannot be changed; it is a constant. The variable or constant
will be assigned initial_value if it is specified or NULL if no initial value
is specified. For more information, see Chapter 2.

Varrays Varrays implement an ordered collection of objects


with a maximum size. They can be manipulated with collection
methods such as DELETE, COUNT, NEXT, and pRlOR. The following
declare section defines a varray type which can hold DATEs:

DECLARE
TYPE t_DaTes IS VARRAY(25) OF DATE;

For more information, see Chapter 12.

zERo-DlvlDE Exception This predefined exception corresponds to


the Oracle error "ORA-1476: divisor is equal to zero". lt is raised whenever
an attempt to divide by zero is performed.
938 OracleS PUSQL Programming

his appendix describes some of therviews in the data


dictionary that are relevant to PL/SQL programmers. lt does
not include all of the views, just the more commonly used
ones. A brief description of the data dictionary and how it
works is also included.

What Is the Data Dictionarl?


The data dictionary is where Oracle stores information about the structure
of the database. The data itself is located in other areas-the data
dictionary describes how the actual data is organized. The dictionary
consists of tables and views that you can query, like any other database
table or view. The views are owned by the Oracle user SYS.
The data dictionary is typically created when the database is created
and installed for the first time. Without the dictionary, no PL/SQL work can
be done. On most systems, there is a script called catproc.sql that creates
the dictionary views. This script should be run while connected as SYS, or
connected as internal in SQL*DBA or Server Manager.
ln addition to creating the data dictionary itself, catproc.sql creates
the standard PL/SQL and DBMS packages, which are stored in the data
dictionary. For more information on the data dictionary views (including
views not discussed here and the v$ performance views), see the OracleT
Server Reference. For more information on the built in packages, see
Appendix B.

Naming Conventions
Many of the views have three different instantiations. These are known as
user_*, all_*, and dba_*. For example, there are three instantiations of the
information about the source for stored objects. The views that represent
this are user-source, all_source, and dba_source. ln general, the user_*
views contain information about objects owned by the current user, the
all * views contain information about all objects accessible to the current
user (not necessarily owned by them), and the dba * views contain
information about all objects in the database.
SQL and PL/SQL are not tase sensitive. ln order to implement this, all
objects are convefted into uppercase before they are stored. Therefore, you
should use uppercase whcn querying the data dictionary. For example, the
user_objects view has a column object name that contains the name of the
Appendix D: The Data DictionarY 939

object. These names are always stored in uppercase. You could query
user-obiects with:

C SQL> SELECT object-tlpe. status


2 FROM user-objects
3 WHERE object-name = IIPPER('ClaEsPackage' ) ;

OBJECT-TYPE STATUS

PACKAGE VAL]D
PACKAGE BODY VALID

Note the use of the UPPER function so that the query will return the desired
rows. (ClassPackage is described in Chapter B')

Permissions
The data dictionary views are owned by sYS. By default, only sYS and
users with the DBA system privilege can see all of the views. Users
without
the DBA privilege can see the user-* and all-* views, in addition to Some
others. They cannot see the dba-* views unless they have been granted
specific SELECT privileges on them.
The data diction"ty-ui"*t should never be updated, even by SYS. They
are updated automaticallyby their r
changes. Oracle also provide fy the
when-a database is uPgraded (such
upgrades from a 7.3.1 database to a 7 abase)
founa in the same directory as catproc'sql'

Al l/User/DBA Dictio nal"f Views


This section describes the data dictionary views that have the user-*, dba-*
and all * instantiations. Since the three instantiations have many columns
in common, they are listed together. Each cateEory is listed in Table D-1
for reference and described in detail in the following sections.

Dependencies
The all_dependencies, dba_dependencies, and user-dependencies
views
documEnt ihe dependency relationship between stored objects.
940 OracleS PUSQL programming

Category Views
Dependencies all_dependencies, dba_dependencies,
user _dependencies
Collections* all_coll_types, dba_coll_types, user_coll_types
Compile Errors all_errors, dba_errors, user_errors
Directories* all directories, dba_directories, user_directories
Jobs all_jobs, dba_jobs, useljobs
LOBs* all_lobs, dba_lobs, user_lobs
Libraries* all libraries, dba_libraries, user_libraries
Object Method all method_params, dba_method_params,
Parameters* user method_params
object Method Results all method_results, dba_method_results,
(return values)* user method results
Object Methods* all_type_methods, dba_type_methods,
user_type_methods
ObjectReferences* all_refs,dba_refs,user_refs
Object Type Anributes+ all_type_attrs, dba_type_attrs, user_type_attrs
Object Types+ all_types, dba_types, user_types
Schema Objects all_objects, dba_objects, user_objects
Source Code all_source, dba_source/ user_source
Table Columns all tab columns, dba_tab_columns,
user tab columns
Tables all_tables, dba_tables, user__tables, all_catalog,
dba_cata log, user_catalog
Triggers all_triggers, dba_triggers, user_triggers
Trigger Columns all_trigger_cols, dba_trigger_cols,
user_tngger cols

TABLE D- l. Data Dictionary Views in this Appendix

* Available in OracleB
anct higher
Appendix D: The Data Dictionary 94a

Column Null? Type Description


OWNER NOT VARCHAR2(30) Schema that owns rhe
NULL objecr (all_dependencies
and dba_dependencies
only).
NAME NOT VARCHAR2(30) Name of the objecr (in
NULL uppercase).
TYPE VARCHAR2(I2) Type of the object___one
of PROCEDURE,
FUNCTION, PACKAGE,
PACKACE BODY.
REFERENCED-OWNER VARCHAR2(3O) Schema rhat owns rhe
referenced clbject.
REFERENCED-NAME VARCHAR2(30) Name of rhe referenced
object.
REFERENCED-TYPE VARCHAR2(12) Type of the referenced
object-one of
PROCEDURE,
FUNCTION, PACKACE,
PACKAGE BODY.
REFERENCED-LINK- VARCHAR2(128) Name of the database
NAME link to the referenced
object (if the referenced
object is in a remote
database).

Collections
The all_coll_types, dba_coll_types, and user_coll_types views
contain information about the collections accessible to the
user. only collection types which are defined with the CREATE TypE
statement (as opposed to those local to a pLlSeL block) are stored in the
data dictionary.
942 Oracle8 PUSeL programming

Column Null? Type Description


OWNER NOT VARCHAR2(30) Schema which owns the
NULL col lection (all_coll_types
and dba_coll_types on ly)
TYPE NAME NOT VARCHAR2(30) Name of the collection
NULL
COLL TYPE NOT VARCHAR2(30) Col lection type---either
NULL TABLE oT VARYING ARRAY
UPPER BOUND NUMBER Maximum number of
elements for varray types
ELEM-TYPE-MOD VARCHAR2(7) Element type modifier (such
as REF)
ELEM-TYPE-OWNER VARCHAR2(30) Owner of the element type
(if different from the owner
of the collection itselfl
ELEM-TYPE_NAME VARCHAR2(30) Name of the element type
LENCTH NUMBER lf the element type is CHAR
or VARCHAR2, its length
PRECISION NUMBER lf the element type is
NUMBER, the specified
prectston
SCALE NUMBER lf the element type is
NUMBER, the specified scale
CHARACTER SET vARCHAR2(44) Character set name if
NAME specified-CHAR_CS
or NCHAR CS

Compile Errors
The all-errors, dba-errors, and user_errors views contain the text of
compile errors for stored objects and views. lf there is an entry in one of the
_errors views, then the object is necessarily invalid (indicated in
all_objects, dba_objects, and user_objects).
A typical query of user._errors. might look like this:

SELECT line, position, text


FROM user errors
WHERE name = object_name
ORDER BY sequence;
Appendix D: The Data Dictionary 943

Column Null? TyPe Description


OWNER NOT VARCHAR2(30) Schema that owns the object
NULL (all_errors and dba_errors only).
NAME NOT VARCHAR2(30) Name of the object (in
NULL uppercase).
TYPE VARCHAR2(12) Type of the object----one of
VIEW, PROCEDURE,
FUNCTION, PACKAGE,
PACKAGE BODY.
SEQUENCE NOT NUMBER Sequence number, used to order
NULL the errors.
LINE NOT NUMBER Line number at which the
NULL error occurs.
POSITION NOT NUMBER Zero-based offset within the line
NULL at which the error occurs.
TEXT NOT VARCHAR2(2OOO) Text of the error, including
NULL both the error code and the
error message.

Directories
ffi ffi ::;,:!"'-ffi ,*i:? ji:;fnffi ;:t1,*x,$:r;u:L::#j"
of directories (for BFILEs) on the operating system. For more information,
see Chapter 21.

Column Null? Type Description


OWNER NOT VARCHAR2(3O) Schema which owns the
NULL directory (all_directories
and user_directories on ly)
DIRECTORY_NAME NOT VARCHAR2(30) Name of the directory
NULL
DIRECTORY-PATH Nor VARCHAR2(4000) operaring system path of
NULL the directory on the
file system

f obs
The alljobs, dbajobs, and user_jobs views contain information
about database jobs.
944 OracleS PUSQL Programming

Column Null? TyPe Description


JOB NOT NUMBER Job lD number. As long as the
NULL job exists, this lD will remain
the same.
LOC USER NOT VARCHAR2(30) User who submitted the job.
NULL
PRIV USER NOT VARCHAR2(30) User whose default privileges
NULL apply for this job.
SCHEMA USER NOT VARCHAR2(30) Default schema for the job.
NULL
LAST DATE DATE Date when the job last
successfu I ly executed.
LAST SEC VARCHAR2(8) Same as last_date, in
HH24:Ml:SS format.
THIS DATE DATE Date the job started executing.
NULL if the job is not currently
running.
THIS SEC VARCHAR2(8) Same as this_date, in
HH24:Ml:SS format.
NEXT DATE NOT DATE Date when the job will next
NULL be executed.
NEXT SEC VARCHAR2(B) Same as next_date, in
HH24:Ml:SS format.
TOTAL TIME NUMBER Total time in seconds spent by
the system on this job.
BROKEN VARCHAR2(1) Y if the job is broken, N if not.
INTERVAL NOT VARCHAR2(2OO) Date function which is used to
NULL calculate the next value of
next date.
FAILURES NUMBER Number of failures since the
last successful run of this job.
WHAT VARCHAR2(2OOO) Body of the anonymous
PL/SQL block making up the
job.
CURRENT SESSION RAW MLSLABEL Trusted OracleT Server label of
LABEL the current job session.
Appendix D: The Data Dictionary 945

Column Null? T)rpe Description


CLEARANCE_HI RAW MLSLABEL Highest clearance level
available for the job (Trusted
OracleZ only).
CLEARANCE_LO RAW MLSLABEL Lowesr clearance level
available for the job (Trusted
OracleZ only).
NLS_ENV VARCHAR2(2000) NLS environmenr for the job
(as specified by ALTER
SESSION).
MISC_ENV RAW(32) Other session parameters for
the job.

Libraries
The all-libraries, dba-libraries, and user_libraries views specify the
operating system location for shared libraries, used for external
procedures. For more information, see Chapter 20.

Column Null? Datatype Description


OWNER NOT VARCHAR2(30) Schema which owns the
NULL I ibrary (all_libraries and

dba_libraries only)
LIBRARY NAME NOT VARCHAR2(3O) Name of the library
NULL
FILE SPEC VARCHAR2(2000) Operating system patch of
the library on the file system
DYNAMIC VARCHAR2(1) Y if the library is dynamic, N
if not
STATUS VARCHAR2(7) Library status-VAltD or
INVALID

LOBs
The all_lobs, dba_lobs, and user_lobs contain information about
LOBs contained in tables accessible by the current user.
945 OracleS pUSeL programming

Column Null? Datatype Description


OWNER NOT VARCHAR2(30) Schema of the table which
NULL contains the LOB (all lobs and
dba_lobs only)
TABLE NAME NOT VARCHAR2(30) Name of the table containing
NULL the LOB
COLUMN NAME VARCHAR2(4OOO) Name of the LOB column
or attribute
SECMENT NAME NOT VARCHAR2(30) Name of the LOB segment
NULL
INDEX NAME NOT VARCHAR2(30) Name of the LOB index
NULL
CHUNK NUMBER Size of the LOB chunk as a
unit of allocation or
manipulation, in byies
PCTVERSION NOT NUMBER Maximum percentage of the
NULL LOB storage used for versioning
CACHE VARCHAR2(3) YES if the LOB is accessed
through the buffer cache, NO
otherwise
LOGGING VARCHAR2(3) YES if LOB changes are logged,
NO otherwise
IN ROW VARCHAR2(3) YES if some of the LOB is
stored with the base row, NO
otherwise

Object Methods
I he all_type_methods, dba_
The dba_type_methods, and userJype_methods
views contain information about the methods in the objectiypes
accessible to the current user.

Column Null? Datatype Description


OWNER NOT VARCHAR2(30) Owner of the object type
NULL (all_type_methods and
dba_type_methods on ly)
TYPE NAME NOT VARCHAR2(30) Name of the object type
NULL
Appendix D: The Data DictionarT 947

Column Null? Datatype Description


METHOD NAME NOT VARCHAR2(30) Name of the method
. NULL
METHOD_NO NOT NUMBER Method number (used for
NULL distinguishing between
overloaded methods)
METHOD_TYPE VARCHAR2(6) Type of the method----one of
MAP, ORDER, or PUBLIC
PARAMETERS NOT NUMBER Number of parameters for
NULL the method
RESULTS NOT NUMBER Number of results returned by
NULL the method

Object Metho d P ararneters


ffi ffi J5,l,;ffi :l_ili*lalX.lili'.fl 3i-#""*?j;'jilil';1?fl "0,.,
the accessible object types. The *_method_params, *-method-results, and
*_type_methods views together completely describe the methods available.

Column Nutl? Datatype Description


OWNER NOT VARCHAR2(3O) Schema which owns the
NULL object type
(all_method_params and
dba_method_params on ly)
TYPE-NAME NOT VARCHAR2(3O) Name of the object tyire
NULL
METHOD NAME NOT VARCHAR2(3O) Name of the method
NULL
METHOD NO NOT NUMBER Method number (used for
NULL distinguishing between
overloaded methods)
PARAM NAME NOT VARCHAR2(3O) Parameter name
NULL
PARAM NO NOT NUMBER Parameter number
NULL or position
PARAM MODE VARCHAR2(6) Parameter mode (lN, OUT,
or lN OUT)
948 OracleS PUSQL Programming

Column Null? Datatype Description


PARAM TYPE MOD VARCHAR2(Z) parameter type modifier
(such as REF)
PARAM TYPE OWNER VARCHAR2(3O) Owner of the type of the
parameter (if a user-defined
type)
PARAM TYPE NAME VARCHAR2(3O) parameter type name
CHARACTER SET NAME VARCHAR2(44) Character set of the
parameter, if specified

Object Method Results


ffi ffi :[:'ffi-#:l*j*";11"",':1il?;,X';1""11,'X-,Ji',h*,"
information about the methods in the oUj".t types accessible to the user.
However, the *-method-results views contain information about the return
values of those methods which are functions.

Column Null? Datatype Description


OWNER NOT VARCHAR2(30) Schema which owns the
NULL type (all_method_results
and dba method results
only)
TYPE_NAME NOT VARCHAR2(3O) Name of the object type
NULL
METHOD_NAME NOT VARCHAR2(3O) Method name
NULL
METHOD_NO NOT NUMBER Method number (used for
NULL distinguishing between
overloaded methods)
RESULT_TYPE_MOD VARCHAR2(7) Type modifier (such as REF)
for the return value
RESULT_TYPE_OWNER VARCHAR2(30) Owner of the type of
the return value, if a
user-defined type
RESULT_TYPE_NAME VARCHAR2(30) Name of the type of the
return value, if a
user-defined type
Appendix D: The Data Dictionary 949

Column Null? Datatype Description


CHARACTER SET NAME VARCHAR2(44) Character set of the return
value, if specified

Object References
The all_refs, dba-refs, and user refs views contain information
about the columns in the tables accessible to the user which are
REF types.

Column Null? Datatype Description


OWNER NOT VARCHAR2(30) Owner of the table
NULL (all refs and dba refs
only)
TABLE NAME NOT VARCHAR2(30) Name of the table
NULL containing the
REF column

COLUMN NAME VARCHAR2(4OOO) Name of the column


which contains the
REF type
WITH ROWID VARCHAR2(3) YES if the REF column is
stored with the ROWID,
NO otherwise
IS SCOPED VARCHAR2(3) YES if the REF column is
scoped, NO otherwise
SCOPE TABLE OWNER VARCHAR2(30) lf the REF column is
scoped, the schema of
the scope table
SCOPE TABLE NAME VARCHAR2(30) lf the REF column is
scoped, the name of the
scope table

Object Type Attributes


The al l_type_attrs, dba_type-attrs, and user-type-attrs views
contain information about the attributes of the object types
accessible to the user.
950 OracleS PUSQL Programming

Column Null? Datatype Description


OWNER VARCHAR2(30) Schema which owns the
object type (all_type_attrs
and dba_type_attrs on ly)
ryPE NAME NOT VARCHAR2(30) Name of the object type
NULL
ATTR NAME NOT VARCHAR2(30) Name of the aftribute
NULL
ATTR TYPE MOD VARCHAR2(7) Type modifier (such as
REF) of the attribute
ATTR TYPE OWNER VARCHAR2(30) Owner of the type of the
attribute, if it is a
user-defined type
LENCTIJ NUMBER Length of a CHAR or
VARCHAR2 attribute
PRECISION NUMBER Precision of a NUMBER
attribute
SCALE NUMBER Scale of a NUMBER
aftribute
CHARACTER_SET-NAME VARCHAR2(44) Character set of the
aftribute, if specified

Schema Objects
The all-obfects, dba_objects, and user_objects views contain information
about all types of schema objects, including tables, stored subprograms,
views, sequences, and indexes. Object types are described in ihe
*_type_methods, *_method_;rarams, *_method_results, *
*_types views. _type_attrs, and

Column Nutl? Type Description


OWNER NOT VARCHAR2(30) Schema that owns the object
NULL (all_objec.ts and dba_objects
only).
OBJECT_NAME NOT VARCHAR2(3O) Name of the object
NULL (in uppercase).
oBJECT_tD NOT NUMBER Object number. Every database
NULL object is assigned a unique lD.
Appendix D: The Data Dictionary 95 I

Column Null? Type Description


OBJECT-TYPE VARCHAR2(12) Type of the object (TABLE,
PACKAGE BODY, SEQUENCE,
PROCEDURE, etc.).
CREATED NOT DATE Timestamp when the object
NULL was created.
LAST DDL TIME NOT DATE Timestamp when the last DDL
NULL operation (such as an ALTER)
was performed on the object.
GRANTs and REVOKEs also
modify this timestamp.
TIMESTAMP VARCHAR2(75) Creation timestamp, in
YYYY-MM-DD: H H24:Ml :SS
format.
STATUS VARCHAR2(7) Object status-VALtD,
INVALID, or N/A.

Source Code
The all source, dba_source, and user_source views contain the source
code for stored procedures, functions, packages, and package bodies.
Trigger source code is in the all_triggers, dba_triggers, and userJriggers
views. lf the stored object is wrapped, these views contain the encoded
source rather than clear te>ct.
A typical query of the user_source table might look like this:

SELECT text
FROM user source
WHERE NAME = object_name
ORDER BY LINE.

Column Null? Type Description


OWNER NOT NULL VARCHAR2(30) Schema that owns
the object
(all source and
dba_source only).
NAME NOT NULL VARCHAR2(30) Name of the stored
object.
952 OracleS PUSQL Programming

Column Null? Type Description


TYPE VARCHAR2(12) Type of the object.
Valid values are
PACKACE,
PACKACE BODY,
PROCEDURE, and
FUNCTION.
LINE NOT NULL NUMBER Line number for
this line of source
code.
TEXT VARCHAR2(2OOO) Text source at
this line.

Tables
The all rables, dba-tables, and user_tables views contain information
about database tables. This information is for the table itself. column
information is stored in all_tab_columns, dba_tab columns, and
user tab columns.

Column Null? Type Description


OWNER NOT VARCHAR2(30) Schema that owns the table
NULL (all_tables and dba tables
only).
TABLE NAME NOT VARCHAR2(30) Name of the table
NULL (in uppercase).
TABLESPACE NAME NOT VARCHAR2(30) Name of the tablespace
NULL containing the table.
CLUSTER NAME. VARCHAR2(30) Name of the cluster to which
the table belongs. NULL if
the table is not clustered.
PCT FREE NOT- NUMBER Minimum percentage of free
NULL space in a block, specified at
table creation, or when the
table was last ALTERed.
PCT USED NOT NUMBER Minimum percentage of used
NULL space in a block, specified at
table creation, or when the
table was last ALTERed.
Appendix D: The Data Dictionary 953

Column Null? Type Description


INI TRANS NOT NUMBER lnitial number of transactions,
NULL specified at table creation, or
when the table was last
ALTERed.
MAX TRANS NOT NUMBER Maximum number of
NULL transactions, specified at
table creation, or when the
table was last ALTERed.
INITIAL EXTENT NUMBER Size of the initial extent in
bytes, if specified.
NEXT EXTENT NUMBER Size of the next extent in
bytes, if specified.
MIN EXTENTS NUMBER Minimum number of extents
allowed in the segment,
if specified.
MAX EXTENTS NUMBER Maximum number of extents,
if specified.
PCT INCREASE NUMBER Percentage increase al lowed
in extent size, if specified.
FREELISTS NUMBER Number of process freelists
allocated to the segrnent,
if specified.
FREELIST GROUPS NUMBER Number of freelist groups
allocated to the segment,
if specified.
BACKED UP VARCHAR2(1) Y if the table has been
backed up since the last
change, N if not.
NUM ROWS NUMBER Number of rows in the table.
BLOCKS NUMBER Number of data blocks
allocated to the table.
EMPTY BLOCKS NUMBER Number of data blocks
allocated that contain no
data. (empty-blocks / blocks)
* 1 0O is the percentage used.
AVC SPACE NUMBER Average amount of free space
in an allocated data block,
in bytes.
954 OracleS PUSQL Programming

Column Null? Type Description


CHAIN CNT NUMBER Number of rows in the table
that are chained over more
than one block.
AVG ROW LEN NUMBER Average row length, in bytes.
DEGREE VARCHAR2('10) Number of threads per
instance for scanning the
table (parallel server only).
INSTANCES VARCHAR2(10) Number of instances across
which the table will be
scanned (parallel server only).
CACHE VARCHAR2(5) Y if the table is cached in the
buffer cache, N if not.
TABLE LOCK VARCHAR2(8) ENABLED if table locking is
enabled, DISABLED if not.

The all_catalog, dba_catalog, and user_catalog views provide a subset


of the information in all_tables, dba_tables, and user_tables.

Column Null? Type Description


OWNER NOT VARCHAR2(30) Schema that owns the
NULL object (all_catalog and
dba_catalog only)
TABLE NAME NOT VARCHAR2(30) Name of the object
NULL (in uppercase)
TABLE TYPE VARCHAR2(1 1) Type of the object
(TABLE, VIEW,
SYNONYM, SEQUENCE)

Table Columns
The al l_tab_col umns, dba_tab_columns, and userJab_columns vi ews
contain information about columns in database tables, views, and clusters.
When an object is described, this table is queried.
Appendix D: The Data Dictionary 955

Column Null? Type Description


OWNER NOT vARCHAR2(30) Schema that owns the object
NULL (all tab columns and
dba_tab_columns only).
TABLE NAME NOT VARCHAR2(30) Name of the table, view,
NULL or cluster.
COLUMN NAME NOT VARCHAR2(30) Name of the column.
NULL
DATA TYPE VARCHAR2(9) Datatype of the column
(NUMBER, CHAR, DATE,
etc.).
DATA LENCTH NOT NUMBER Maximum length of the
NULL column in bytes.
DATA PRECISION NUMBER Decimal precision for
NUMBER columns, binary
precision for FLOAT
columns. NULL for other
datatypes or when the
precision is not specified.
DATA SCALE NUMBER Scale for NUMBER columns.
NULL for other datatypes
or when the scale is not
specified.
NULLABLE VARCHAR2(1) 'Y' if the column allows
NULLs, 'N' if not.
COLUMN ID NOT NUMBER Unique value assigned to the
NULL column. All columns have an
lD associated with them.
DEFAULT LENGTH NUMBER Length of the default value
for the column, if specified.
DATA DEFAULT LONC Default value fc' rhe column,
if specified.
NUM DISTINCT NUMBER Number of distinct values in
the column.
956 OracleS pUSeL programming

Column Null? Type Description


LOW VALUE RAW(32) Second lowest value in the
table (4 rows or more), or
lowest value in the table (3
rows or less). Stored as the
internal representation of the
first 32 bytes of the column.
HIGH VALUE RAW(32) Second highest value in the
table (4 rows or more), or
highest value in the table (3
rows or less). Stored as the
internal representation of the
first 32 bytes of the column.
DENSITY NUMBER Density of the column.
NUM NULLS NUMBER Number of rows which
contain NULL values.
NUM_BUCKETS NUMBER Number of buckets used
when ANALYZing the table.
LAST ANALYZED DATE Timestamp when the table
was last ANALYZEd.
SAMPLE SIZE NUMBER Sample size used during the
last ANALYZE.

Triggers
The all_triggers, dba_triggers, and userJriggers views
describe the
oarabase triggers accessible to the user. All of the different
components in
the CREATE TRlccER statement are corumns in these
views.

Column Null? Type Description


OWNER NOT VARCHAR2(30) Schema rhat owns the
NULL rrigger (ail_triggers and
dba_triggers only).
TRICCER NAME NOT VARCHAR2(30) Name of the trigger (in
NULL uppercase).
Appendix D: The Data Dictionary 957

Column Null? Type Description


TRIGGER TYPE VARCHAR2(16) Trigger type-BEFORE
ROW, BEFORE
STATEMENT, AFTER
ROW, AFTER
STATEMENT.
TRIGCERINC EVENT VARCHAR2(26) DML statement that fires
the trigger----one or more
of INSERT, UPDATE,
DELETE.
TABLE OWNER NOT VARCHAR2(30) Owner of the table
NULL on which the trigger
is defined.
TABLE NAME NOT VARCHAR2(30) Name of the table
NULL on which the trigger
is defined.
REFERENCINC NAMES VARCHAR2(87) lf specified, names used
for referencing :old and
:new in row-level triggers.
WHEN CLAUSE VARCHAR2(2OOO) WHEN clause of the
trigger, if specified.
STATUS VARCHAR2(8) ENABLED if the trigger is
enabled, DISABLED if not.
DESCRIPTION VARCHAR2(2OOO) Character string
containing the trigger
name, trigger type,
WHEN clause, and
referencing clause, as
specified in the CREATE
TRIGGER statement.
Useful for re-creating the
statement if the source
file is lost.
TRICCER BODY LONC PL/SQL block making up
the body of the trigger.
958 Oracle8 PUSQL Programming

Trigger Columns
The al l-trigger-cols, dba_tri gger_cols, and userJri gger_cols v ews show
i

the usage of columns in database triggers. These views -mplement the


al l_tri ggers, dba_triggers, and userJri ggers v ews.
i

Column Null? Type Description


TRIGGER-owNER Nor VARCHAR2(30) schema rhat owns the trigger.
NULL
TR|GGER-NAME Nor VARCHAR2(3O) Name of the trigger (in
NULL uppercase).
TABLE-OWNER Nor VARCHAR2(30) schema thar owns the table
NULL on which the trigger is
defined.
TABLE-NAME Nor VARCHAR2(3O) Name of the table on which
NULL the trigger is defined (in
uppercase).
COLUMN-NAME Nor VARCHAR2(30) Name of the column used in
NULL the trigger
coLUMN-Llsr VARCHAR2(3) yES if the column is specified
in the UPDATE clause, NO
if not.
coLUMN-usAcE VARCHAR2(17) specifies how the column is
referenced in the trigger. All
applicable combinations of
NEW, OLD, lN, OUT, and
IN OUT.

Views
The all-views, dba-views, and user_views views describe the views in the
database.

Column Null? Type Description


OWNER NOT VARCHAR2(3O) Schema rhat owns the view
NULL (all views and dba views
only).
VIEW_NAME NOT VARCHAR2(30) Name of rhe view
NULL (in uppercase).
Appendix D: The Data Dictionary 959

Column Null? Type Description


TEXT_LENCTH NUMBER Length of the view text.
TEXT LONC Text of the view-the body of
the CREATE VIEW statement.

other Dictionar.f views


ln addition to the views described in the previous section, there are two
other data dictionary views that are useful to the PL/SQL programmer. They
are described in this section, listed alphabetically.

dbms_alert_info
The dbms alert info view contains information about sessions that have
registered interest in alerts.

Column Null? Type Description


NAME NOT VARCHAR2(3O) Name of the alert for which
NULL the session has registered
interest.
SID NOT VARCHAR2(3O) Session identifier.
NULL
CHANCED VARCHAR2(3O) Y if the alert has been
signaled, N if not.
MESSACE VARCHAR2(I800) Message that is included in
the SICNAL call, if any.

dict_columns
The dict_columns view describes all of the columns in the data dictionary.

Column Null? Type Description


TABLE_NAME VARCHAR2(3O) Name of the data
dictionary view.
COLUMN_NAME VARCHAR2(30) Column in the view.
COMMENTS VARCHAR2(2000) Description of the column.

You might also like