Oracle PLSQL Quickref
Oracle PLSQL Quickref
40021GC10
Production 1.0
April 1999
M08685
ORACLE'
Oracle PL/SQL Quick Reference
Edition 1.0
Text
The text in this reference adheres to the following conventions:
UPPERCASE Uppercase text calls attention to SQL keywords, filenames, andinitialization
parameters.
italics Italicized text calls attention to parameters of SQL statements.
boldface Boldface text calls attention to definitions of terms.
Required keywords and parameters can appear singly or in a vertical list of alternatives. Single
%mum.
required keywords and parameters appear on the main path, that is, on the horizontal line you are
currently traveling. In the following example,library_name is a required parameter:
If there is a library named HQ_LIB, then, according to the diagram, the following statement is valid:
SAVEPOINT sl;
If multiple keywords or parameters appear in a vertical list that intersects the main path, one of them
is required. That is, you must choose one of the keywords or parameters, but not necessarily the one
that appears on the main path. In the following example, you must choose one of the four settings:
• 42
0
Multipart Diagrams
Read a multipart diagram as if all the main paths were joined end to end. The following example is a
two-part diagram:
PUBLIC im . r--(achema
H CREATE SYNONYM (synonym>
-- (schema—, 0 CD
FOR -(objec)
0
According to the diagram, the following statement is valid:
CREATE SYNONYM emp FOR scott.employees;
Database Objects
The names of Oracle identifiers, such as tables and columns, must not exceed 30 characters in length.
The first character must be a letter, but the rest can be any combination of letters, numerals, dollar
signs ($), pound signs (#), and underscores (_).
However, if an Oracle identifier is enclosed by double quotation marks ("), it can contain any
combination of legal characters, including spaces but excluding quotation marks.
Oracle identifiers are not case-sensitive except when enclosed by double quotation marks.
Note: In this quick reference guide, not all syntax statements have been included, and of those
included, not all clauses have been included. For further information, secOracle8 SQL Reference.
Composite Types
RECORD
TABLE
VARRAY
Reference Types
REF CURSOR
REF object_type
LOB Types
BFILE
BLOB
CLOB
NCLOB
PROCEDURES
System Privilege Allows Grantee To ...
CREATE PROCEDURE Create stored procedures, functions, and
packages in grantee's schema
CREATE ANY PROCEDURE Create stored procedures, functions, and
packages in any schema except SYS
ALTER ANY PROCEDURE Alter stored procedures, functions, or
packages in any schema except SYS
DROP ANY PROCEDURE Drop stored procedures, functions, or
packages in any schema except SYS
EXECUTE ANY PROCEDURE Execute procedures or functions (standalone
or packaged)
Reference public package variables in any
schema except SYS
TRIGGER
System Privilege Allows Grantee To ...
CREATE TRIGGER Create a database trigger in grantee's schema
CREATE ANY TRIGGER Create database triggers in any schema except
SYS
ALTER ANY TRIGGER Enable, disable, or compile database triggers
in any schema except SYS
DROP ANY TRIGGER Drop any trigger in any schema except SYS
ADMINISTER DATABASE Create a trigger on DATABASE (You must
TRIGGER also have the CREATE TRIGGER or
CREATE ANY TRIGGER privilege.)
TYPES
System Privilege Allows Grantee To ...
CREATE TYPE Create object types and object type bodies in
Grantee's schema
CREATE TYPE Create object types and object type bodies in
any schema except SYS
ALTER ANY TYPE Alter object types in any schema except SYS
DROP ANY TYPE Drop object types and object type bodies in
any schema except SYS
EXECUTE ANY TYPE Use and reference object types and collection
types in any schema except SYS, and invoke
methods of an object type in any schemaif you
make the grant to a specific user (If you grant
EXECUTE ANY TYPE to a role, users
holding the enabled role will not be able to
invoke methods of any object type in any
schema.)
TABLE PRIVILEGES
ALTER Change the table definition with the ALTER TABLE
statement
DELETE Remove rows from the table with the DELETE statement
Note: You must grant the SELECT privilege on the table
along with the DELETE privilege
INDEX Create an index on the table with the CREATE INDEX
statement
INSERT Add new rows to the table with the INSERT statement
REFERENCES Create a constraint that refers to the table. (You cannot
grant this privilege to a role.)
SELECT Queiy the table with the SELECT statement
UPDATE Change data in the table with the UPDATE statement
Note: You must grant the SELECT privilege on the table
along with the UPDATE privilege.
VIEW PRIVILEGES
DELETE Remove rows from the view with the DELETE statement
INSERT Add new rows to the view with the INSERT statement
SELECT Query the view with the SELECT statement.
UPDATE Change data in the view with the UPDATE statement
SEQUENCE PRIVILEGES
ALTER Change the sequence definition with the ALTER
SEQUENCE statement
SELECT Examine and increment values of the sequence with the
CURRVAL and NEXTVAL pseudocolumns
PROCEDURE, FUNCTION, and PACKAGE PRIVILEGE
EXECUTE Compile the procedure or function or execute it directly, or
access any program object declared in the specification of a
package
SNAPSHOT PRIVILEGE
SELECT Queiy the snapshot with the SELECT statement
Built-in Functions
PL/SQL provides many powerful functions to help you manipulate data. These built-in functions fall
into the following categories:
• Error-reporting
• Number
• Character
• Conversion
• Date
• Miscellaneous
You can use all the functions in SQL statements except the error-reporting functions SQLCODE and
SQLERRM. Also, you can use all the functions in procedural statements except the miscellaneous
functions DECODE, DUMP, and VSIZE.
The SQL group functions AVG, MIN, MAX, COUNT, SUM, STDDEV, and VARIANCE are not
built into PL/SQL. Nevertheless, you can use them in SQL statements but not in procedural
statements.
ALTER FUNCTION
ALTER PACKAGE
Use this command to explicitly recompile either a package specification, body, or both.
PACKAGE
SPECIFICATION
ALTER PROCEDURE
Use this command to explicitly recompile a stand-alone stored procedure.
scherna>,( DEBUG
ALTER PROCEDURE (ProcedurD-5, COMPILE -1
schema.
DISABLE
ALTER TRIGGER trigger
DEBUG
COMPILE
DROP FUNCTION
Use this command to remove a stored function from the database.
3chertu
DROP 4 FUNCTION >JP ::Cunction_rtame>f)
DROP PACKAGE
Use this command to remove a stored package from the database. This statement drops the body and
specification of a package.
DROP PACKAGE
DROP PROCEDURE
Use this command to remove a stored procedure from the database.
scherna
DROP 4 PROCEDURE
DROP 4 TRIGGER
,-(collecton_name
AS A
--cursorra rbb le_name)
-0-(1-nstsu rsor_varidDle_nam!)
indicab r_ na me
-0(hastita riable_ria
ccoremionX)
attrki ute_nam--)
bject_name
-(para meter_name)
fie Id_namDm
-Creccrd_rie me )
frarieble_rte me)
Block
The basic program unit in PL/SQL is the block.
plsql_block
el_name DECLARE
BEGIN ) statement
L ()
type_def in it i on
-Crefsursor_type definition
eollectio n_declaratio
-(constant_declaratio r)
-Gursor_declaratioD
--Crecord_decia rotor)
'-(tar iable_decbration)
assig nmentstrte me nty
-(exit_stateme nD
-Goto_staie me nit)
statement
-(f_stite menD
kbel_name -Qoop_statemen)
—4
-Cn ul l_stateme nD
- l_b bel)
-Eaise_sk3 temen)
E
- ft u rn_sterte me nt..)
--(sq (_statement)
sql statement
k bse_statvmenD
-Calm mitstatemen)
-Cdelete_sttemenD
<fetchstatement
-(lock_table statemen)
Cope n_skatemen)
-Gpe niNo r_statemer7)
-Csarepointstat me nt)
--Cselect_slatemen)
-Cset_transaction_staie me n)-
\-(±6) date_state me n)
„-Cunctior)—,
cblink_name
CALL procedure)
method-3
INDICATOR
(rxlicator_variabl
INTO kit variable
CLOSE Statement
The CLOSE statement enables resources held by an open cursor or cursor variable to be reused. No
more rows can be fetched from a closed cursor or cursor variable.
close_statement
.--Gursor_name)
kotsursor_raridole_name)-)
DELETE
OCD
EXISTS OAA
EXTEND
0 C1:110
collection_name
FIRST
LAST
LIMIT
NEXT
ASO
PRIOR opo
number
TRIM
Collection
A collection is an ordered group of elements, all of the same type (for example, the grades for a class
of students). Each element has a unique subscript that determines its position in the collection.
PL/SQL offers three kinds of collections: index-by tables, nested tables, andvarrays.
tab'e type_def in it ion
NOT NULL
TYPE -type_ro me IS TABLE OF -felement type7))
INDEX BY BINARY_INTEGER
-1_ 0
varray type_definition
VAR RAY
--) TYPE - type_name IS size_limit
VARRYING ARRAY
collection declaration
kursor_name ROWTY PE
ROWTYPE
--(db_tzble_name
mlumn_name TYPE
<object_name TYPE
REF
object_type_name
--recd rd_type_na me
<scalardatatype_name
<variable_rome TYPE
Comments
Comments can appear within a statement at the end of a line. You cannot nest comments.
comment
• CD
40 0 lb
COMMIT Statement
The COMMIT statement explicitly makes permanent any changes made to the database during the
current transaction.
commit statement
WORK
COMMIT
datatype
-Collecion_na me
r TYPE
-(cmllection_type_ria me
ROWTYP E
-(2 Jib le_name
cx)lu mn_name TYPE
-(object_name TYPE
REF
(object_type_name
-Crew rd_name TY PE
- recordtype me)
-Cref_curso r_type_name
'-variable_reme TYPE
constant declaration
SQL ROWOOU NT
Cursor Variable
To execute a multirow query, Oracle server opens an unnamed work area that stores processing
information. To access the information, you can use an explicit cursor, which names the work area.
Or you can use a cursor variable, which points to the work area.
ref_eu rsor_type_definition
do table_reme ROWTY PE
--(cursor_name ROWTYP E
—Cm:or d_type_name
%-Crefcursor_type_name
cursor_var ► le _name
cursorpararneter declaratbn
CURSOR -(cursor_name
RETURN
grommilf
cursor spec
CURSOR
RETURN -4 rowtyFe
cursor body
curaorparameter declaration
H CURSOR -.Eursor_name
.
cursor_parameter_declaration
erp remior)-1
IN DEFAULT
f
----(parameter_name) e
rowtype
c(db_tkle_name ROWTYPE
-(cursor_name . ROWTYPE
-Cecord_name TYPE
Qecord_type_rome
„-((earch_cond ition)
WHERE
)-1
CU RRE NT OF cursor_ name
rE etur ning_cia use)--1.
table reference
I-Ctiew_rra me.)
returning_clause
<var &le_name
slog le_row_expre5sio n)-L INTO
\-CyChost_var iable_na me
RETURNING
BULK COLLECT
\----Cmultiale_row_expression)-- INTO
EXCEPTION_INIT PRAGMA
The PRAGMA EXCEPTION_INIT associates an exception name with an Oracle error number. This
enables you to refer to any internal exception by name and to write a specific handler for it instead of
using the OTHERS handler.
exception_init_pregma
—(exoeption_name)-> EXCEPTION
exception jandler
Ft exception_rome
exception name
WHEN THEN statement-4
OTHERS
*.k
—(...0define _vari±le_name>—,
INTO
reoord_rome
1._ )
IN
OUT
IN OUT
ti USING bind_argume rrt_na me
EXIT Statement
You use the EXIT statement to exit a loop.
exit statement
-Cdat_exp ression
boolean expression
,Cocc. lean_constantnam ,
-C.,colean_fu nctonsaD
NOT
(boo iean_Iiteral
OR
Qicio lean_liter
kc.olean_vari±le_name)--
othe r jooleanjor
NOT
r 1—‘ LIKE
T
f BETW EE N
kxpres•sion.> AND exp remio
NOT
- IN exp ressiLD
cu mr_n3 me
FOU ND
rsoutariit le_name
ISO P EN
-hast cu rso r_var le_na me
ICTFOLIND
SQL
cliarecter expression
kharwier_functio n_caII
-Ccharacterliteral
—4,
-Ccharanter_va ri&le_name)
ind kat° rro me
-04Chot va nab le_na me
-Ciatefunctio n_caD
date hie ra I
nu me ric_expre3sio
) -
n umerie_express i on
cursor_name
--Gursor riable_na me
ROMIG() U NT
host cursor ya rith le_name)--
SQL
indicator na me
--(1-post va riab le_ro me
k umeric_constartro me)
expone nt
- umeric fu actio n cal)
- umeric_lit ra I
FIRST
LAST
c Ileciton_na me
LIMIT
NEXT opo
PRIOR 000
riable_na me
INTO 4—
\-(r.ezo rd_na me)
c~l lection_name
L BU LK COLLECT INTO
host ar ray_name
FO RAU -.(index_nam;)- IN
--Cql_31atemen)-0
Functions
A function is a subprogram that can take parameters and be invoked. Generally, you use a function to
compute a value.
f unction_spec
paramete r deciaratio n
EU ICTION unction_na me)
R ETU RN -(d3tatypiD-0
parameter declaration
FU NCTION ,Qunction_rra me
RETU RN IS 4
. —>
BEGIN ; L-Qtate me nt)1
labelna
g oto_statement
GOTO -(labsl_name>f)
',1111411
IF Statement
The IF statement lets you execute a sequence of statements conditionally. Whether the sequence is
executed or not depends on the value of a Boolean expression.
if statement
ELSE statment->)---
END IF
INSERT Statement
The INSERT statement adds new rows of data to a specified database table or view.
insert statement
,-(iable_referenoe)
INSERT INTO
Vimminit
TABLE subquery2
O re rnin g_cb
VALUES sql_exprenion
tbquery3
intege
K
L-Cea riterir
integer
real_number
character_literal
string_literal
-0-
bo °lea nl ite rel
TRUE
FALSE
NULL —
NOINAIT
—I LOCK TABLE table_refe re nae IN -(ica_rnzide), MO DE
el_name
LOOP
while_loop_statement
label_name
WHILE ,)Coacilean_expre&sion>
.,(Ethe(_name)—.1,_
—4 LOOP state men END LOOP
for_loop statement
LeI_name
FOR 4(index_name> IN 4
REVERSE
pper_bounc)-->
Cower_bound
name)--.
—1 LOOP statement))--4 END LOOP
.1=1•111/
cursor for_loop_statement
IN
Ilimmose
cursor_parameter_na
cursor_name
select statement
..1111.111
LOOP state men). —i END LOOP ,f 0
NULL Statement
The NULL statement explicitly specifies inaction; it does nothing other than pass control to the next
statement. In a construct allowing alternative actions, the NULL statement serves as a placeholder.
nullstatement
NULL
CURRENT USER
AUTHID
DEFINER IS
AS
M
MEMBER HiCunction_tody
ORDER J
OPEN Statement
The OPEN statement executes the multirow query associated with an explicit cursor. It also allocates
resources that Oracle uses to process the query, and it identifies the result set, which consists of all
rows that meet the query search criteria.
open statement f
I
cu rso r_pa ra meter_name
OPEN rso r_nis me)
fl
OPEN-FOR Statement
The OPEN-FOR statement executes the multirow query associated with a cursor variable. It also
allocates resources that Oracle server uses to process the query, and it identifies the result set, which
consists of all rows that meet the query search criteria.
open statement
cu rso r_parameter_name
OP EN rso r_na me
O
USING
C aind_arg umentnarne)
*am,. Package
A package is a schema object that groups logically related PL/SQL types, items, and subprograms.
Packages have two parts: a specification (spec for short) and a body.
package_declaration package spec
type_definition -.
am/
—Cnecord_type_defin itis
CURRENT USER
ALITHID ckage_ite m_decia raton)—
DEFINER IS
(cursor_wee)
gmataile AS
—(unction_we
--Cprcxedu re ..sFe)
package_body
OR REPLACE ~Ir s+c he rna_na me
CREATE PACKAGE EC DY Frac e_namD4
n_deci3 ration).
(tar ithledeclaratbr)
Procedure
A procedure is a subprogram that can take parameters and be invoked. Generally, you use a
procedure to perform an action.
procedure spec
procedure_body procedure_declaration
<type_def in ition)—,
1 unction_deck3 ralion)-Th
I •
I H-Chem_decia ration rocedure_ded3 ratorD-•
BEGIN . statement
p roped u re_name
›-)
EXCEPTIO N
Queption_handler END
parameter_declaration
IN
OUT NO00 PY
1 >)
IN OUT
-.(paramete rita me) ) aara P
.1.100.0 exception_name
J
RAISE fl
Records
Records are items of type RECORD. Records have uniquely named fields that can store data values of
different types.
record type definition
record declaration
RETURN Statement
The RETURN statement immediately completes the execution of a subprogram and returns control to
the caller. Execution then resumes with the statement following the subprogram call. In a function, the
RETURN statement also sets the function identifier to the result value.
1mM
return_statement
RETURN
ROLLBACK Statement
The ROLLBACK statement is the inverse of the COMMIT statement. It undoes some or all database
changes made during the current transaction.
rollback statement
SAVEFOINIT
WORK TO swepoint_name
H ROLLBACK
SAVEPOINT Statement
The SAVEPOINT statement names and marks the current point in the processing of a transaction.
With the ROLLBACK TO statement, savepoints enable you to undo parts of a transaction instead of
the whole transaction.
save point_stateme nt
UNIQUE
ALL O
SELECT
•••Cselect_item
,--)-(variable_nameym
INTO
..--(ecord_name.)
--*
oDllection_rume)
BULK COLLECT INTO
host_ar ray_name
table_reie re nae
FROM 5ubque
TABLE subquery,
parameter_riame
,(function_rnme))
NULL
ra)
schema_name <table_na
AS
<wiew_name)--i-C albs
schema_name r-(teble_name
-view_rta me-
oolumn_name
CLIRRVAL
-Csequence_name
NEX1VAL
• 0fl
SET TRANSACTION Statement
The SET TRANSACTION statement begins a read-only or read-write transaction, establishes an
isolation level, or assigns the current transaction to a specified rollback segment.
set transaction statement
READ ONLY
READ WRITE
SQL Cursor
The Oracle server implicitly opens a cursor to process each SQL statement that is not associated with
an explicit cursor. PL/SQL lets you refer to the most recent implicit cursor as the SQL cursor, which
has four attributes: %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. These attributes
give you useful information about the execution of data manipulation statements.
sql_cursor
FOU ND
ISO P EN
SQL
NOTFOU ND
RO1 COO LI NT
SQLCODE
SQLERRM Function
The function SQLERRM returns the error message associated with its error-number argument or, if
the argument is omitted, with the current value of SQLCODE. SQLERRM with no argument is
meaningful only in an exception handler. Outside a handler, SQLERRM with no argument always
returns the message of a normal, successful completion.
sq lerrmiu n cti on
e rror_number
SQLERRM
%TYPE Attribute
The %TYPE attribute provides the datatype of a field, record, nested table, database column, or
variable. You can use the %TYPE attribute as a datatype specifier when declaring constants,
variables, fields, and parameters.
type attribute
--ab,ject_namf)
--Crecord_rta me
<var iable_na me
rCdml_everrt_clause
OR
dml_event_clause
OR
DELETE
INSERT
OF column
UPDATE
ON
referencing_clause
OLD
AS
REFERENCING NEW
AS
ti PARENT parent FOR EACH ROW
lab le_referenoe)
albs
-H UPDATE 0 subquerD-0
TABLE subRuery2
sql_expremion)
,Koolumn_name
subquery3
SET ti
<-5earch_conditor)
WHERE
CU RRENT OF -.i.C.;ursor_rome r—Eeturning_ciause)-1
-