Directory listing of http: uap.unnes.ac.id ebook biblebook Visual Basic 6 com & Library Books

28
C H A P T E R

Creating Stored
Procedures with
Oracle8i









In This Cha pter
Intro ducing PL/ SQ L

I

n this c hapter, I’m go ing to disc uss the details o f ho w to

c reate vario us pro c edural o bjec ts, suc h as sto red pro c edures and func tio ns. I’ll also disc uss Orac le’s implementatio n
o f SQL and the extensio ns nec essary to pro vide a ric h pro gramming enviro nment.

Introducing PL/ SQL
Every database vendo r has its o wn variatio n o f the SQL language, and Orac le is no exc eptio n. Pro c edural Language/ SQL,
also kno wn as PL/ SQL, c o ntains a series o f extensio ns that
make it po ssible to build effic ient pro grams whic h c an perfo rm c o mplex database func tio ns.
PL/ SQL is used primarily to build sto red pro c edures and func tio ns. These ro utines essentially bec o me an extensio n to the
PL/ SQL language. Thus, yo u c an c all yo ur o wn sto red pro c edure as easily as yo u wo uld use a Select statement. In fac t, it
may be easier to c all a sto red pro c edure than use a Select
statement, sinc e sto red pro c edures typic ally have fewer
parameters.

Comments
Co mments in PL/ SQL are the same as SQL Server’s T-SQL.
Do uble hyphen c o mments ( --) mark the start o f a c o mment
who se text c o ntinues to the end o f the line. Slash asterisk,
asterisk slash c o mments ( /* */) c an be used anywhere a
spac e c an be used, and may span multiple lines.


W riting sto red
pro cedures in PL/ SQ L
Creating a packag e









628

Part VII ✦ Oracle8i

Constants
String values must be enc lo sed in single quo tes ( ‘), as sho wn belo w:

‘This is a string constant.’

If yo u wish to embed a single quo te in a string c o nstant, simply use two single
quo tes to gether, like this:

‘This is a ‘’string’’ with embedded single quotes.’
This string c o nstant wo uld be understo o d by PL/ SQL as:

This is a ‘string’ with embedded single quotes.
Caution

Quote’th the raven, never double: Double quotes ( “) are not the sam e thing as
tw o single quotes ( ‘ ‘). Double quotes are used to indicate case-sensitive identifiers, w hile tw o single quotes inside a string constant indicate that a single single
quote should be inserted at that position.

Numbers, as yo u might expec t, may begin with a plus sign ( +) o r a minus sign ( -),
fo llo wed by a series o f numeric digits, a dec imal po int, and mo re digits. So me examples o f numbers are:

0

3.1415926


1000.0

-100.001

+512

Dates , whic h are sto red internally in a spec ial fo rmat, are written like strings,
exc ept theyare fo rmatted as DD-MM-YY. Fo r example,

‘27-Jul-65’

‘27-Jul-1965’

‘1-May-2000’

are valid Date c o nstants.

Identifiers
An identifier c an be up to 30 c harac ters in length. They must begin with a letter and
may c o ntain letters, numbers, and the undersc o re c harac ter ( _ ) . Identifiers are used

as the name o f a sto red pro c edure o r func tio n, as a lo c al variable, and as the name o f
vario us database o bjec ts. Do uble quo tes ( “ ) surro und identifiers that c o ntain
spac es o r spec ial c harac ters.

Variables
PL/ SQL allo ws yo u to define lo c al variables that c an be used in sto red pro c edures
and func tio ns. They are dec lared in the Declare sec tio n o f yo ur pro c edure. Yo u c an

Chapter 28 ✦ Creating Stored Procedures with Oracle8i

dec lare a variable to be o f any data type suppo rted by Orac le8i. Unlike SQL Server,
variables need no t begin with a spec ial c harac ter. Any identifier that do esn’t c o nflic t with an Orac le8i keywo rd may be used.
CrossReference

See the discussion of Oracle8 i data types in Chapter 26 if you w ould like to
becom e m ore fam iliar w ith them .

Functions
PL/ SQL pro vides a number o f func tio ns that c an be used to perfo rm c alc ulatio ns o r
data c o nversio ns. So me o f the mo re interesting func tio ns are listed in Table 28-1.


Table 28-1
Selected Functions in PL/ SQL
Function

Description

Add_months

Adds the specified num ber of m onths to the specified date.

ASCII

Returns the ASCII code of the left-m ost character of the specified
character string.

Ceil

Returns the sm allest integer value greater than or equal to the
specified value.


Chr

Returns the character corresponding to the specified num eric
ASCII code value.

Floor

Returns the largest integer value less than or equal to the
specified value.

Initcap

Capitalizes the first character of each w ord in a string.

Instr

Returns the position of the specified search string in a specified
data string.


Last_day

Returns the date of the last day of the m onth for the specified
data value.

Length

Returns the size of a string, num ber, date, or expression.

Lower

Converts all uppercase characters to low ercase.

Ltrim

Rem oves leading blanks from a character string.

M od

Com putes the rem ainder after dividing the tw o values.

Continued

629

630

Part VII ✦ Oracle8i

Table 28-1 (continued)

Tip

Function

Description

M onths_between

Com putes the num ber of m onths betw een tw o dates.


New_time

Converts a Date value to the specified tim e zone.

Next_day

Returns a Date value containing the day that follow s the
specified date.

Replace

Replaces the search string w ith a replacem ent string in the
specified string.

Round

Rounds the specified Number or Date value to the specified
accuracy.

Rtrim


Rem oves trailing blanks from a character string.

Substr

Returns a string of characters from the specified string w ith the
specified starting location and length.

Sysdate

Returns the current date and tim e.

To_char

Converts the specified value to a character string.

To_date

Converts the specified value to a Date value.

To_number

Converts the specified value to a num eric value.

Trunc

Truncates the specified Date or Number value using the
specified accuracy.

Upper

Converts all low ercase characters to uppercase.

User

Contains the user nam e of the current user.

If you don’t like these, then build your own: If you need a function that isn’t
available in PL/ SQL, you can easily build your ow n using the Create Function
statem ent. Functions are a variation on stored procedures. The only difference is
that a function returns a single value that can be used as part of an expression,
w hile a stored procedure can’t be used as part of an expression.

Block structure
The blo ck structure is the fundamental way statements are o rganized into a sto red
pro c edure o r func tio n. A b lo c k struc ture is b ro ken into three main sec tio ns, the
De clare sec tio n, the main b o dy and the Exce ption sec tio n. The De clare sec tio n is

Chapter 28 ✦ Creating Stored Procedures with Oracle8i

used to dec lare b lo c k-wide variab les. These variab les c an b e used in b etween the
Be gin and End statements. Yo u may o ptio nally assign an initial value fo r these
variab les.
The Begin statement marks the start o f the exec utable c o mmands sec tio n o f the
blo c k. When the blo c k is c alled, c o ntro l will begin with the first statement fo llo wing
the Begin statement. Pro gram flo w will c o ntinue until it reac hes either the End statement o r the Exception statement. When either o f these statements is reac hed, exec utio n is c o mplete and c o ntro l will return to the c alling pro gram.
If an erro r o c c urs while running in the exec utable c o mmands sec tio n o f the blo c k,
c o ntro l will be transferred to the first statement fo llo wing the Exception statement.
If the Exception sec tio n isn’t present, an erro r message will be returned to the c alling pro gram. Onc e yo u transfer c o ntro l the to Exception sec tio n, yo u c an’t return
to the exec utable c o mmands sec tio n.
Note

Nesting: A block can be used anyw here a PL/ SQL statem ent can be used.
Thus, you can nest one block inside of another. In the innerm ost block, you
can use any of the variables declared in the outer blocks. How ever, you can’t
use any of the variables declared in an inner block once you are outside that
block. The syntax for a block is:

>
[Declare
[:= ];
[ [:= ];] ...
]
Begin
;
[;]...
[Exception
When Then ; [;]...
[When Then ; [;]...]...
]
End []; where is an identifier that is asso c iated with
the blo c k; is an identifier that will be used to sto re info rmatio n lo c ally
in the blo c k; . is any legal Orac le8i data type; is a
c o nstant that is appro priate fo r the data type; is any legal PL/ SQL
statement o r c o mmand; and is an exc eptio n (see Table 28-2), a list o f
exc eptio ns that are Or’ed to gether, o r the keywo rd Others , whic h traps any remaining exc eptio ns.

631

632

Part VII ✦ Oracle8i

Table 28-2
Exceptions

Note

Exception

Description

CURSOR_ALREADY_OPEN

An Open statem ent tried to open a cursor that w as already
open.

DUP_VAL_ON_INDEX

An Insert or Update statem ent created a duplicate value in
a Unique index.

INVALID_CURSOR

An Open statem ent tried to open an undefined cursor; a
Close statem ent tried to close a closed cursor; a Fetch
statem ent tried to use an unopened cursor, and so on.

INVALID_NUMBER

An illegal num eric value w as found w hen trying to convert
a character string to a num eric value.

LOGIN_DENIED

The user nam e and passw ord com bination w as invalid in a
Connect statem ent.

NO_DATA_FOUND

A Select statem ent returned zero row s.

NOT_LOGGED_ON

An attem pt w as m ade to access database resources
w ithout being connected to the database.

PROGRAM_ERROR

A catchall error used by PL/ SQL to trap its ow n errors.

STORAGE_ERROR

Insufficient m em ory w as available to execute the function,
or the available m em ory w as corrupted (possible
subscripting error).

TIMEOUT_ON_RESOURCE

A resource w asn’t available w hen it should have been.

TOO_MANY_ROWS

A Select statem ent that should return a single row
returned m ore than one row.

TRANSACTION_BACKED_OUT

A rem ote part of a transaction failed and w as rolled back.

VALUE_ERROR

A conversion error, a truncation error, or a precision error
affecting a variable or colum n value occurred

ZERO_DIVIDE

An attem pt w as m ade to divide by zero.

Blockhead: The nam e of a block is an optional feature that m arks the beginning
of a block. It is sim ply an identifier that is enclosed in double less than ( ) signs, such as . The sam e nam e that
begins the block m ust also be specified in the End statem ent, like this:End
MyBlock.

Chapter 28 ✦ Creating Stored Procedures with Oracle8i

Procedures, functions, and packages
Pro c edures and func tio ns c o ntain c o de that c an be treated as an extensio n to
PL/ SQL. A pro c edure c an be used in muc h the same way as a c o mmand o r SQL
statement, while a func tio n c an be inc o rpo rated into any expressio n. Pro c edures
and func tio ns c an be written as standalo ne ro utines o r c o mbined in a single unit
c alled a package . (The Create Package statement is explained at the end o f this
c hapter.)
Note

Just a routine check: Procedures and functions are basically the sam e thing. The
only difference is in how they are used. Functions can be used w ithin an expression, w hile a procedure m ust be called as a separate statem ent I use the term
“routine” to refer to som ething that can be either a procedure or a function. For
instance, I m ight say that “Routines have param eters” rather than saying “Procedures and functions have param eters”. Not only does this m ake things a little
clearer, it also saves m e a lot of typing.

Procedures and functions
Pro c edures and func tio ns are just blo c ks with a header that defines the name o f a
partic ular ro utine and the list o f parameters asso c iated with it. A pro c edure is similar to a Visual Basic subro utine in ho w it is used. Yo u pass a series o f parameters to
a pro c edure as a single statement. When it finishes, c o ntro l is returned to the next
statement in yo ur pro gram.
A PL/ SQL func tio n wo rks like a Visual Basic func tio n. It is used in an expressio n to
c o mpute a value based o n a set o f parameters. When the func tio n returns its value,
the rest o f the expressio n is pro c essed.
The syntax fo r a pro c edure definitio n is:

Procedure [.]
[( [,]...)]
{Is|As}
The syntax fo r a func tio n definitio n is:

Function [.]
[( [,]...)]
Return
{Is|As}
where is the name o f the user asso c iated with the pro c edure o r func tio n; is the name o f the pro c edure; is the name o f the
func tio n; is [In|Out|In Out] , where
is the name o f the parameter; In means that the parameter is passed
to the ro utine, but any c hanges in the parameter are no t returned to the c alling

633

634

Part VII ✦ Oracle8i

pro gram, Out means that no value is passed to the ro utine, but the ro utine will
return a value to the c alling pro gram, In Out means that a value is passed to the
ro utine and any c hanges in the parameter will be returned to the c alling pro gram,
and is the data type asso c iated with the parameter; and

is a blo c k dec laratio n as I disc ussed in the Blo c k struc ture sec tio n earlier
in this c hapter. It is separated fro m the rest o f the statement by using the Is o r As
keywo rds.

Return statement
The Return statement is used to return a value to the c alling pro gram. It uses the
fo llo wing syntax:

Return();
where is a variable o r expressio n c o ntaining the info rmatio n that will be
returned as the value o f the func tio n.

Packages
A package is merely a single unit c o ntaining a c o llec tio n o f o ne o r mo re pro c edures
and func tio ns (o r ro utines), with so me o ptio nal glo bal variables. It c o rrespo nds to a
Visual Basic mo dule. The pac kage c o nsists o f three parts: glo bal dec laratio ns, whic h
are o ptio nal, at least o ne ro utine, and a blo c k o f c o de that is exec uted eac h time a
ro utine in the pac kage is c alled. This blo c k is exec uted first, whic h allo ws yo u to initialize glo bal variables, o pen a c urso r, o r any o ther lo gic that is c o mmo n to all o f the
ro utines.
Tip

I love packages: Besides the obvious benefit of creating a single installation unit
that com bines m any different routines, packages are often m ore efficient than
independent stored procedures and functions, since the code is com piled
together as a single unit. Thus, you avoid the extra costs of locating the new routine, loading it, and preparing to run it. All of this w ork is done w hen the first routine in the package is called.

Expressions
Yo u c an c o mpute a single value based o n a c o llec tio n o f lo c al variables, parameters,
func tio ns, and c o lumns retrieved fro m a table, and then assign the value to a lo c al
variable o r c o lumn. PL/ SQL uses the assignment o perato r ( :=) to perfo rm the
assignment, as sho wn belo w:

MyVariable := ‘A string value’;
MyNumber := 3.14159265;
MyNumber := MyNumber * 20;

Chapter 28 ✦ Creating Stored Procedures with Oracle8i

Flow control
Orac le8i / SQL suppo rts a wider range o f flo w c o ntro l statements than Mic ro so ft’s
SQL Server. Yo u c an use statements suc h as If, For, and While to c o ntro l the flo w
thro ugh yo ur sto red pro c edure. Yo u c an also c all pro c edures and func tio ns direc tly
witho ut having to use a spec ial statement.

If statement
The If statement has the fo llo wing syntax:

If
{|}
[Elsif
{|}]...
[Else
{|