0% found this document useful (0 votes)
23 views

Oracle PLSQL Quickref

Uploaded by

skorlipa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Oracle PLSQL Quickref

Uploaded by

skorlipa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Oracle PL/SQL Quick Reference

Oracle PL/SQL Quick Reference

40021GC10
Production 1.0
April 1999
M08685

ORACLE'
Oracle PL/SQL Quick Reference

Edition 1.0

Published by Oracle Corporation

Copyright© Oracle Corporation, 1999. All rights reserved.

Author: Kuljit Jassar


This documentation contains proprietary information of Oracle Corporation. It is provided under a license agreement containing
restrictions on use and disclosure and is also protected by copyright law. Reverse engineering of the software is prohibited. If this
documentation is delivered to a U.S. Government Agency of the Department of Defense, then it is delivered with Restricted Rights
and the following legend is applicable:
Restricted Rights Legend
Use, duplication or disclosure by the Government is subject to restrictions for commercial computer software and shall be deemed to
be Restricted Rights software under Federal law, as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013, Rights in
Technical Data and Computer Software (October 1988).
This material or any portion of it may not be copied in any form or by any means without the express prior written permission of
Oracle Corporation. Any other copying is a violation of copyright law and nay result in civil and/or criminal penalties.
If this documentation is delivered to a U.S. Government Agency not within the Department of Defense, then it is delivered with
"Restricted Rights." as defined in FAR 52.227-14, Rights in Data-General, including Alternate III (June 1987).
The information in this document is subject to change without notice. If you find any problems in the documentation, please report
them in writing to Education Products, Oracle Corporation, 500 Oracle Parkway, Box SB-6, Redwood Shores, CA 94065. Oracle
Corporation does not warrant that this document is error-free.
Oracle is a registered trademark and all references to Oracle products are trademarks or registered trademarks of Oracle
Corporation.
All other products or company names are used for identification purposes only, and may be trademarks of their respective owners.

Page 2 Oracle PL/SQL Quick Reference


Table of Contents
Conventions Used in This Reference 5
Syntax Diagrams and Notation 5
Reading Syntax Diagrams 5
Required Keywords and Parameters 5
Optional Keywords and Parameters 6
Syntax Loops 6
Multipart Diagrams 6
Database Objects 6
Datatypes 7
Object Naming Rules 8
Oracle Reserved Words 8
PL/SQL Reserved Words 8
SQL Reserved Words 10
SQL Keywords 11
SYSTEM PRIVILEGES 12
OBJECT PRIVILEGES 13
Built-in Functions 14
SQL Commands Syntax 16
ALTER FUNCTION 16
ALTER PACKAGE 16
ALTER PROCEDURE 16
ALTER TRIGGER 16
DROP FUNCTION 16
DROP PACKAGE 16
DROP PROCEDURE 16
DROP TRIGGER 17
PL/SQL Language Elements 18
Assignment Statement 18
Block 18
CALL 20
CLOSE Statement 20
Collection Method 21
Collection 21
Comments 22
COMMIT Statement 22
Constant and Variable 23
Cursor Attribute 24
Cursor Variable 24
Cursor 25
DELETE Statement 26
EXCEPTION_INIT PRAGMA 26
Exception 27
EXECUTE IMMEDIATE Statement 27
EXIT Statement 27
Expression 28
FETCH Statement 31
FORALL Statement 32

Oracle SQL Language Quick Reference Page 3


Functions 32
GOTO Statement 33
IF Statement 33
INSERT Statement 33
Literal 34
LOCK TABLE Statement 34
LOOP Statement 35
NULL Statement 35
Object Type 36
OPEN Statement 36
OPEN-FOR Statement 36
OPEN-FOR-USING Statement 37
Package 37
Procedure 38
RAISE Statement 39
Records 39
RETURN Statement 39
ROLLBACK Statement 39
%ROWTYPE Attribute 40
SAVEPOINT Statement 40
SELECT INTO Statement 40
SET TRANSACTION Statement 41
SQL Cursor 41
SQLCODE Function 42
SQLERRM Function 42
%TYPE Attribute 42
Trigger 43
UPDATE Statement 44

Page 4 Oracle PL/SQL Quick Reference


Conventions Used in This Reference
.111110P

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.

Syntax Diagrams and Notation


This reference uses syntax diagrams to show PL/SQL statement and other elements of the PL/SQL
language. These syntax diagrams use lines and arrows to show syntactic structure.
If you are not familiar with syntax diagrams, refer toOracle8 SQL Reference.
Keywords appear in UPPERCASE. You must use keywords in your SQL statement exactly as they
appear in the syntax diagram, although keywords are not case-sensitive.
Parameters appear in lowercase and act as placeholders. Parameters are usually names of database
objects, Oracle datatype names, or expressions.

Reading Syntax Diagrams


Syntax diagrams are drawings that illustrate valid SQL syntax. To read a diagram, trace it from left to
right, in the direction shown by the arrows.
Commands and other keywords appear in UPPERCASE inside rectangles. Type them exactly as
shown in the rectangles. Parameters appear in lowercase inside ovals. Variables are used for the
parameters. Punctuation, operators, delimiters, and terminators appear inside circles.
If the syntax diagram has more than one path, you can choose any path to travel.
If you have the choice of more than one keyword, operator, or parameter, your options appear in a
vertical list.
Required Keywords and Parameters
Visomor

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:

SAVEPOINT soveroint name

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

Oracle SQL Language Quick Reference Page 5


Optional Keywords and Parameters
If keywords and parameters appear in a vertical list above the main path, they are optional. In the
following example, instead oftraveling down a vertical line, you can continue along the main path:

roCiabel_ 113 me)-1 WHEN


koolean_expression
EVT )- -
so
According to the diagram, all of the following statements are valid:
EXIT;
EXIT this_loop;
EXIT this_loop WHEN x >= 1000;
Syntax Loops
Loops let you repeat the syntax within them as many times as you like. In the following example, after
choosing one expression, you can go back repeatedly to choose another, separated by commas.

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.

Page 6 Oracle PL/SQL Quick Reference


Datatypes
Scalar Types
BINARY_INTEGER SMALLINT
DEC CHAR
DECIMAL CHARACTER
DOUBLE PRECISION LONG
FLOAT LONG RAW
INT NCHAR
INTEGER NVARCHAR2
NATURAL RAW
NATURALN ROWID
NUMBER STRING
NUMERIC VARCHAR
PLS_INTEGER VARCHAR2
POSITIVE
POSITIVEN BOOLEAN
REAL
SIGNTYPE DATE

Composite Types
RECORD
TABLE
VARRAY

Reference Types
REF CURSOR
REF object_type

LOB Types
BFILE
BLOB
CLOB
NCLOB

Oracle SQL Language Quick Reference Page 7


Object Naming Rules
The following rules apply when naming objects:
• Names must be from 1 to 30 characters long.
• Names cannot contain quotation marks.
• Names are not case-sensitive.
• Unless surrounded by double quotation marks, a name must begin with an alphabetic character
from your database character set.
• Names can contain only alphanumeric characters from your database character set and the
characters underscore(_), dollar sign ($), and pound sign (#). Oracle Corporation strongly
discourages you from using $ and #. Names of database links can also contain periods (.) and at-
signs (@).
If your database character set contains multibyte characters, Oracle recommends that each name
for a user or a role contain at least one single-byte character.
• A name cannot be an Oracle8 reserved word.
Depending on the Oracle product that you plan to use to access a database object, names might be
further restricted by other product-specific reserved words.
• Do not use the word DUAL as a name for an object. DUAL is the name of a dummy table.
• The Oracle SQL language contains other words that have special meanings. These words include
datatypes, function names, and keywords. These words are not reserved. However, Oracle server
uses them internally, and this may make your statements difficult to read and may lead to
unpredictable results

Oracle Reserved Words


Oracle reserved words have special meaning to the Oracle server. You cannot use these words as
names for database objects.
Keywords also have special meaning to Oracle server, but are not reserved words. Because some may
become reserved words, and for maximum portability to other implementations of SQL, do not use
keywords as object names.
PL/SQL Reserved Words
The words listed here are reserved by PL/SQL; that is, they have a special syntactic meaning to
PL/SQL. Thus, you should not use them to name program objects such as constants, variables, and
cursors. Also, some of these words (marked by an asterisk) are reserved by SQL. You should not use
them to name database objects such as columns, tables, and indexes.
ALL* BINARY INTEGER COMMIT DEFAULT*
ALTER* BODY* COMPRESS* DELETE*
AND* BOOLEAN CONNECT* DESC*
ANY* BULK CONSTANT DISTINCT*
ARRAY BY* CREATE* DO
AS* CHAR* CURRENT* DROP*
ASC* CHAR BASE CURRVAL ELSE*
AUTHID CHECK* CURSOR ELSIF
ASSIGN CLOSE DATE* END
AVG CLUSTER* DAY EXCEPTION
BEGIN COLLECT DECLARE EXCLUSIVE*
BETWEEN* COMMENT* DECIMAL* EXECUTE

Page 8 Oracle PL/SQL Quick Reference


EXISTS* MINUTE RAISE TRIGGER*
EXIT MLSLABEL* RANGE TRUE
EXTENDS MOD RAW* TYPE
FALSE MODE* REAL UID*
FETCH MONTH RECORD UNION*
FLOAT* NATURAL REF UNIQUE*
FOR* NATURALN RELEASE UPDATE*
FORALL NEW RETURN USE
FROM* NEXTVAL REVERSE USER*
FUNCTION NOCOPY ROLLBACK VALIDATE*
GOTO NOT* ROW* VALUES*
GROUP* NOWAIT* ROWID* VARCHAR*
HAVING* NULL* ROWLABEL* VARCHAR2*
HEAP NUMBER* ROWNUM* VARIANCE
HOUR NUMBER BASE ROWTYPE VIEW*
IF OCIROWID SAVEPOINT WHEN
IMMEDIATE* OP SECOND WHENEVER*
IN* ON* SELECT* WHERE*
INDEX* OPAQUE SEPARATE WHILE
INDICATOR OPEN SET* WITH*
INSERT* OPERATOR SHARE* WORK
INTEGER* OPTION* SMALLINT* WRITE
INTERFACE OR* SPACE YEAR
INTERSECT* ORDER* SQL ZONE
INTERVAL ORGANIZATION SQLCODE
INTO* OTHERS SQLERRM
IS* OUT START*
ISOLATION PACKAGE STDDEV
JAVA PARTITION SUBTYPE
LEVEL* PCTFREE* SUCCESSFUL*
LIKE* PLS INTEGER SUM
LIMITED POSITIVE SYNONYM*
LOCK* POSITIVEN SYSDATE*
LONG* PRAGMA TABLE*
LOOP PRIOR* THEN*
MAX PRIVATE TIME
MIN PROCEDURE TIMESTAMP
MINUS* PUBLIC* TO*

Oracle SQL Language Quick Reference Page 9


Words followed by an asterisk (*) are also ANSI reserved words.
SQL Reserved Words
ACCESS EXCLUSIVE MODE SELECT*
ADD EXISTS* MODIFY SESSION
ALL* FILE NOAUDIT SET*
ALTER FLOAT* NOCOMPRESS SHARE
AND* FOR* NOT* SIZE
ANY* FROM* NOWAIT SMALLINT*
AS* GRANT* NULL* START
ASC* GROUP* NUMBER SUCCESSFUL
AUDIT HAVING* OF* SYNONYM
BETWEEN* IDENTIFIED OFFLINE SYSDATE
BY* IMMEDIATE ON* TABLE*
CHAR* IN* ONLINE THEN
CHECK* INCREMENT OPTION* TO*
CLUSTER INDEX OR* TRIGGER
COLUMN INITIAL ORDER* UID
COMMENT INSERT* PCTFREE UNION*
COMPRESS INTEGER* PRIOR UNIQUE*
CONNECT INTERSECT PRIVILEGES* UPDATE*
CREATE* INTO* PUBLIC* USER*
CURRENT* IS* RAW VALIDATE
DECIMAL LEVEL RENAME VALUES*
DEFAULT* LIKE* RESOURCE VARCHAR
DELETE* LOCK REVOKE VARCHAR2
DESC* LONG ROW VIEW*
DISTINCT* MAXEXTENTS ROWID WHENEVER
DROP MINUS ROWNUM WHERE*
ELSE MLSLABEL ROWS WITH*

Page 10 Oracle PL/SQL Quick Reference


Words followed by an asterisk (*) are also ANSI reserved words.
SQL Keywords
ADMIN END* MIN* RESTRICTED
AFTER ESCAPE* MINEXTENTS REUSE ROLE
ALLOCATE EVENTS MINVALUE ROLES
%mom/

ANALYZE EXCEPT MODULE* ROLLBACK*


ARCHIVE EXCEPTIONS MOUNT SAVEPOINT
ARCHIVELOG EXEC* NEXT SCHEMA*
AUTHORIZATION* EXECUTE NEW SCN
AVG* EXPLAIN NOARCHIVELOG SECTION*
BACKUP EXTENT NOCACHE SEGMENT
BECOME EXTERNALLY NOCYCLE SEQUENCE
BEFORE FETCH* NOMAXVALUE SHARED
BEGIN* FLUSH NOMINVALUE SNAPSHOT
BLOCK FORCE NONE SOME*
BODY FOREIGN* NOORDER SORT
CACHE FORTRAN* NORESETLOGS SQLCODE*
CANCEL FOUND* NORMAL SQLERROR*
CASCADE FREELIST NOSORT STATEMENT_ID
CHANGE FREELISTS NUMERIC* STATISTICS
CHARACTER* FUNCTION OFF STOP
CHECKPOINT GO* OLD STORAGE
CLOSE* GOTO* ONLY SUM*
COBOL* GROUPS OPEN* SWITCH
COMMIT* INCLUDING OPTIMAL SYSTEM
COMPILE INDICATOR* OWN TABLES
CONSTRAINT INITRANS PACKAGE TABLESPACE
CONSTRAINTS INSTANCE PARALLEL TEMPORARY
CONTENTS INT* PASCAL* THREAD
CONTINUE* KEY* PCTINCREASE TIME
CONTROLFILE LANGUAGE* PCTUS ED TRACING
COUNT* LAYER PLAN TRANSACTION
CURSOR* LINK PLI* TRIGGERS
CYCLE LISTS PRECISION* TRUNCATE
DATABASE LOGFILE PRIMARY* UNDER
DATAFILE MANAGE PRIVATE UNLIMITED
DBA MANUAL PROCEDURE* UNTIL
DEC* MAX* PROFILE USE
DECLARE* MAXDATAFILES QUOTA USING
DISABLE MAXINSTANCES READ WHEN
DISMOUNT MAXLOGFILES REAL* WRITE
DOUBLE* MAXLOGHISTORY RECOVER WORK*
DUMP MAXLOGMEMBERS REFERENCES*
EACH MAXTRANS REFERENCING
ENABLE MAXVALUE RESETLOGS

Oracle PL/SQL Quick Reference Page l I


SYSTEM PRIVILEGES

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.)

Page 12 Oracle PL/SQL Quick Reference


OBJECT PRIVILEGES
These privileges apply to specific objects.
Object Privilege Allows Grantee To ...
ALL [PRIVILEGES] All of the object privileges that can be applied

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

Oracle PL/SQL Quick Reference Page 13


Procedures,
Object Functions, User-Defined
Privilege Table View Sequence Packages Type
ALTER X X
DELETE X X
INDEX X
INSERT X X
READ
REFERENCES X
SELECT X X X
UPDATE X X
EXECUTE X X

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.

Page 14 Oracle PL/SQL Quick Reference


Error Number Character Conversion
SQLCODE ABS ASCII CHARTOROWID
SQLERRM ACOS CHR CONVERT
ASIN CONCAT HEXTORAW
ATAN INITCAP RAWTOHEX
ATAN2 INSTR ROWIDTOCHAR
CEIL INSTRB TO CHAR
COS LENGTH TO DATE
COSH LENGTHB TO_MULTI_BYTE
EXP LOWER TO NUMBER
FLOOR LPAD TO_SINGLE_BYT
E
LN LTRIM
LOG NLS_INITCAP
MOD NLS_LOWER
POWER NLS UPPER
ROUND NLSSORT
SIGN REPLACE
SIN RPAD
SINH RTRIM
SQRT SOUNDEX
TAN SUBSTR
TANH SUBSTRB
TRUNC TRANSLATE
TRIM
UPPER

Date Object Reference Miscellaneous


ADD_MONTHS DEREF BFILENAME
LAST_DAY REF DECODE
MONTHS_BETWEE VALUE DUMP
N
NEW_TIME EMPTY_BLOB
NEXT_DAY EMPTY_CLOB
ROUND GREATEST
SYSDATE LEAST
TRUNC NLS_CHARSET_DECL_LEN
NLS_CHARSET_ID
NLS_CHARSET_NAME
NVL
SYS_CONTEXT
SYS_GUID
UID
USER
USERENV
VSIZE

Oracle PL/SQL Quick Reference Page 15


SQL Commands Syntax
ALTER FUNCTION
Use this command to recompile an invalid stand-alone stored function.

ALTER FUNCTION

ALTER PACKAGE
Use this command to explicitly recompile either a package specification, body, or both.
PACKAGE

SPECIFICATION

„<whema)--, DEBUG BODY


ALTER 4 PACKAGE pa.:1(ag." COMPILE

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

Page l6 Oracle PL/SQL Quick Reference


DROP TRIGGER
Use this command to remove a database trigger from the database.

DROP 4 TRIGGER

Oracle PL/SQL Quick Reference Page 17


PL/SQL Language Elements
Assignment Statement
An assignment statement sets the current value of a variable, field, parameter, or element.
assignment statement

,-(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

e-Ctyp e_def in ition)--. 1..--Ounctio n_declaraijor)Th

‘-(iemdecb ratior)-' roced ure_deciarator),

BEGIN ) statement
L ()

EXCEPTION > (l&coeption_handler 1±el_name


j) END

type_def in it i on

(Crew rd_type_defi nal° n

-Crefsursor_type definition

-021D le_type_def in bon

\-Cva may_type_defin bon

Page 18 Oracle PL/SQL Quick Reference


item declaration

eollectio n_declaratio

-(constant_declaratio r)

-Gursor_declaratioD

kur3or va riable_decb ration.>


-(exceptiondeclaratio

-cob jectdecia ratio ri)

--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

-Cnsert state rrre nt)

-(lock_table statemen)

Cope n_skatemen)
-Gpe niNo r_statemer7)

--(ro Ibmk_slate me nt)

-Csarepointstat me nt)

--Cselect_slatemen)

-Cset_transaction_staie me n)-

\-(±6) date_state me n)

Oracle PL/SQL Quick Reference Page 19


CALL
Allows you to execute a stand-alone procedure or function, or a procedure or function defined within
a type or package.

„-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)

CLOSE ,--cursorva rib le_name)

kotsursor_raridole_name)-)

Page 20 Oracle PL/SQL Quick Reference


Collection Method
A collection method is a built-in function or procedure that operates on collections and is called using
dot notation. The methods EXISTS, COUNT, LIMIT, FIRST, LAST, PRIOR, NEXT, EXTEND,
TRIM, and DELETE help generalize code, make collections easier to use, and make your applications
easier to maintain.
coilection_metkiod_call
COUNT

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

Oracle PL/SQL Quick Reference Page 21


element_type

kursor_name ROWTY PE

ROWTYPE
--(db_tzble_name
mlumn_name TYPE

<object_name TYPE

REF
object_type_name

-Crew rd_name TYPE

--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

Page 22 Oracle PL/SQL Quick Reference


Constant and Variable
You can declare constants and variables in the declarative part of any PL/SQL block, subprogram, or
package. Declarations allocate storage space for a value, specify its datatype, and name the storage
location so that you can reference it. Declarations can also assign an initial value and impose the NOT
NULL constraint.
varbble_deelatati on
(IT remior)—,
DE FAU LT

datatype

-Collecion_na me
r TYPE

-(cmllection_type_ria me

-(curso r_na me Ft0INTY PE

- cursor rith le_name TY PE

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

-(sca lardatatype _name)

'-variable_reme TYPE

constant declaration

Oracle PL/SQL, Quick Reference Page 23


Cursor Attribute
Cursors and cursor variables have four attributes that give you useful information about the execution
of a data manipulation statement.
cursor attribute
cursor_name) FOU ND I,

--cursor Ira riable_ria me ISOPEN

host cursor varithle_name NOT FOU ND

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

TYPE -(type_re me> IS REF CURSOR

do table_reme ROWTY PE

--(cursor_name ROWTYP E

-(cursor uarbble_re ROWTY P E


R ETU RN
<reoord_ro TYPE

—Cm:or d_type_name

%-Crefcursor_type_name

cursor varia ble_declarati on

cursor_var ► le _name

Page 24 Oracle PL/SQL Quick Reference


Cursor
To execute a multirow query, the Oracle server opens an unnamed work area that stores processing
information. A cursor enables you to name the work area, access the information, and process the
rows individually.
cursor declaration

cursorpararneter declaratbn
CURSOR -(cursor_name

RETURN

grommilf
cursor spec

CURSOR

RETURN -4 rowtyFe

cursor body

curaorparameter declaration
H CURSOR -.Eursor_name
.

RETURN rowtype -4 IS select statement

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

Oracle PL/SQL Quick Reference Page 25


DELETE Statement
The DELETE statement removes entire rows of data from a specified table or view.
delete statement
-(tab le _refe re m)

„-((earch_cond ition)
WHERE

)-1
CU RRE NT OF cursor_ name
rE etur ning_cia use)--1.

table reference

,-(ib_tila le_ name db lin k_name)—,

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

PRAGMA EXCEPTION_INIT exception name e fro r_nu rrber os

Page 26 Oracle PL/SQL Quick Reference


Exception
An exception is a run-time error or warning condition, which can be predefined or user-defined.
Predefined exceptions are raised implicitly (automatically) by the run-time system. User-defined
exceptions must be raised explicitly by RAISE statements. To handle raised exceptions, you write
separate routines called exception handlers.
exception_declatation

—(exoeption_name)-> EXCEPTION

exception jandler

Ft exception_rome
exception name
WHEN THEN statement-4
OTHERS

EXECUTE IMMEDIATE Statement


The EXECUTE IMMEDIATE statement prepares (parses) and immediately executes a dynamic SQL
statement or an anonymous PL/SQL block.
execute_immediste_statement

—J EXECUTE IMMEDIATE Kayromic_strinj)+

*.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

label_name)--1 —4 WHEN 4CEcolean_erpressior)mt.


—31 EXIT

Oracle PL/SQL Quick Reference Page 27


Expression
An expression is an arbitrarily complex combination of variables, constants, literals, operators, and
function calls.
expression
,..(boolea n_exp ressio

-Cho race r_exp restsio rp-

-Cdat_exp ression

'<nu me ric_exp reusio

boolean expression
,Cocc. lean_constantnam ,

-C.,colean_fu nctonsaD
NOT
(boo iean_Iiteral

-boo lean_varith le_name>-

\-Cithe r_Loolea njor rn)

--(boo lean_oonsia ntname>

<i)colean_fu irtio n_ca


AND NOT

OR
Qicio lean_liter
kc.olean_vari±le_name)--
othe r jooleanjor

Page 2S Oracle PL/SQL Quick Reference


other_boolean form
relationa l_cperato r exp remb n

-(fLo 1.1ection_na me EXISTS


C 09
NOT
IS

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

(charazter oa nsta nt_na me

kharwier_functio n_caII
-Ccharacterliteral
—4,
-Ccharanter_va ri&le_name)
ind kat° rro me
-04Chot va nab le_na me

(chs racie r_constant_name)

--Ccha racie r_function_call)

-ha rack r_lite ra I


-(charasie ryar iable_ro me.)
indicator name
\-(Xiot_var le_na me

Oracle PL/SQL Quick Reference Page 29


d ate_expression

,-(date co nsta nt_na me)

-Ciatefunctio n_caD

date hie ra I

-(date va riable_rta me)


r_rta me
• tust_ra Ebb le_na me) >)

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

-(n umericya riab le_na me


COUNT

FIRST

LAST
c Ileciton_na me
LIMIT

NEXT opo
PRIOR 000

Page 31) Oracle PL/SQL Quick Reference


--I FETCH cursor ra riab le_ro me

\-0-(Lort_eurso rya riab le_name)

riable_na me
INTO 4—
\-(r.ezo rd_na me)

c~l lection_name
L BU LK COLLECT INTO
host ar ray_name

Oracle PL/SQL Quick Reference Page 31


FORALL Statement
The FORALL statement instructs the PL/SQL engine to bulk-bind input collections before sending
them to the SQL engine. Although the FORALL statement contains an iteration scheme, it is not a
FOR loop.
fang Il_staterne nt

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

function_body I fun ction_declaration

parameter declaration
FU NCTION ,Qunction_rra me

RETU RN IS 4

..-Cype_defin ition)--, I ...-Cunction_decbraton)—,


I )
m_decia ratior)--. 1
-(procedure_deciaraijon>..
ti

. —>
BEGIN ; L-Qtate me nt)1

EXCEPTION exceptla n_handle r


END

pare mete r_dec larati on

--<paramete r_rra me) ) (datatypO)

Page 32 Oracle PL/SQL Quick Reference


GOTO Statement
The GOTO statement branches unconditionally to a statement label or block label.
label...declaration

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

-)boolean_expressior)). THEN > (CsiatemenD-L

ELSIF -.(boalean_eyprmb THEN > 1:-(3tatement

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

Oracle PL/SQL Quick Reference Page 33


Literal
A literal is an explicit numeric, character, string, or Boolean value not represented by an identifier.
The numeric literal 135 and the string literal ' hello world' are examples.
n umeric literal

intege
K
L-Cea riterir
integer

real_number

character_literal

string_literal

-0-
bo °lea nl ite rel

TRUE

FALSE

NULL —

LOCK TABLE Statement


The LOCK TABLE statement enables you to lock entire database tables in a specified lock mode. In
this way you can share or deny access to the tables while maintaining their integrity.
locktable_statement

NOINAIT
—I LOCK TABLE table_refe re nae IN -(ica_rnzide), MO DE

Page 34 Oracle PL/SQL Quick Reference


LOOP Statement
The LOOP statement executes a sequence of statements multiple times. The loop encloses the
sequence of statements that is to be repeated. PL/SQL provides basic loops, WHILE loops, FOR
loops, and cursor FOR loops.
basic_loop statement

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

Oracle PL/SQL Quick Reference Page 35


Object Type
An object type is a user-defined composite datatype that encapsulates a data structure along with the
functions and procedures needed to manipulate the data. The variables that form the data structure are
called attributes. The functions and procedures that characterize the behavior of the object type are
called methods.
object_type_declaration I object_type spec

r--)1 OR REPLACE sc: he ma_na me


CREATE TYPE type_name)4

CURRENT USER
AUTHID
DEFINER IS

AS

MAP MEMBER - program_spec


MEMBER function_wec
ORDER STATIC -Ceal l_srec
0 •
object type_body

OR REPLACE h ache rro_na me


CREATE TYPE BODY pe_name
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

Page 36 Oracle PL/SQL Quick Reference


OPEN-FOR-USING Statement
The OPEN-FOR-USING statement associates a cursor variable with a multirow query, executes the
query, identifies the result set, positions the cursor on the first row in the result set, then zeroes the
rows-processed count kept by %ROWCOUNT.
open for_using statement

cum:4 va noble ra me)


OPEN FOR 4Cdynamic_str ing)
host cursor varbble_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

OR REPLACE ..H,p(sche ma _na me


—41 CREATE >1 PACKAGE Foe e_name

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)

' -cal sped

package_body
OR REPLACE ~Ir s+c he rna_na me
CREATE PACKAGE EC DY Frac e_namD4

—(package_iie m_decia ration


IS BEGIN statement r- Foe- e_name
(!ursor_sper) END
AS
(functbn_sFej)
package_item_declaration

n_deci3 ration).

-Cagotantdecla ratio r)-

--(exception_decia ratio r)-

-Cch ject_decla ration


-(record_decla ratio n)

(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

ra mete r_decb ration


PROCEDURE -)Cp roced ure_ro me) •

procedure_body procedure_declaration

pa ra mete r_decla ration


PROCEDURE -(procedure_rra me-) > IS

<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

Page 38 Oracle PL/SQL Quick Reference


RAISE Statement
The RAISE statement stops normal execution of a PL/SQL block or subprogram and transfers control
to the appropriate exception handler.
rain statement

.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

TYPE <type_ro IS RECORD field declaratbn AA

..1•011, NOT NULL


f ield_declaration

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

Oracle PL/SQL Quick Reference Page 39


% ROWTYPE Attribute
The %ROWTYPE attribute provides a record type that represents a row in a database table. The
record can store an entire row of data selected from the table or fetched from a cursor or cursor
variable. Fields in a record and corresponding columns in a row have the same names and datatypes.
rowtype attribute

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

SAVE POI NT savepoint name

SELECT INTO Statement


The SELECT INTO statement retrieves data from one or more database tables, then assigns the
selected values to variables or fields.
se le ct_i nt o statement
DISTINCT

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,

Page 40 Oracle PL/SQL Quick Reference


select item

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

SET TRANSACTION SERIALIZABLE


ISOLATION LEVEL H READ MMMITTED

USE ROLLBACK SEGMENT <rolback_segment_name>

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

Oracle PL/SQL Quick Reference Pare 41


SQLCODE Function
The function SQLCODE returns the number code associated with the most recently raised exception.
SQLCODE is meaningful only in an exception handler. Outside a handler, SQLCODE always returns
0.
sqlcode jun cti on

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

((col lectia n_name)

—Gursor_va ri3ble_na me)

--ab,ject_namf)

--Crecord_rta me

<var iable_na me

Page 42 Oracle PL/SQL Quick Reference


Trigger
A trigger is a stored PL/SQL block associated with a table, a schema, or the database.
r.- BEFORE
OR REPLACE FA,. schema
CREATE TRIGGER tr igger AFTER
ly
INSTEAD OF

rCdml_everrt_clause

OR

ddl event hema


SCHEMA
OR
DATABASE
\--(datatese_event

WHEN condition klhql_black)


--(referencing_clause)))
1-(callprocedure_statement)-1-4

dml_event_clause
OR

DELETE

INSERT

OF column
UPDATE

ON

referencing_clause

OLD

AS
REFERENCING NEW

AS
ti PARENT parent FOR EACH ROW

Oracle PL/SQL Quick Reference Page 43


UPDATE Statement
The UPDATE statement changes the values of specified columns in one or more rows in a table or
view.
u pd ate_state men t

lab le_referenoe)
albs
-H UPDATE 0 subquerD-0

TABLE subRuery2

sql_expremion)
,Koolumn_name
subquery3
SET ti

> kolumn_name 000 subquely4

<-5earch_conditor)
WHERE
CU RRENT OF -.i.C.;ursor_rome r—Eeturning_ciause)-1
-

Pare 44 Oracle PL/SQL Quick Reference


Oracle is a registered trademark of Oracle Corporation. All Oracle product
ORACLE® names are trademarks or registered trademarks of Oracle Corporation.
All other companies and product names mentioned are used for indentifi-
cation purposes only, and may be trademarks of their respective owner.

Copyright © Oracle Corporation 1998


All Rights Reserved

You might also like