• Tidak ada hasil yang ditemukan

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

N/A
N/A
Protected

Academic year: 2017

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

Copied!
20
0
0

Teks penuh

(1)

Creating Stored

Procedures with

Oracle8i

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 e-dures 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 lan-guage, 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 per-fo 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 e-dure as easily as yo u wo uld use a Se le ctstatement. In fac t, it may be easier to c all a sto red pro c edure than use a Se le ct 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.

2 8

2 8

In This Cha pter

Intro ducing PL/ SQ L W riting sto red

pro cedures in PL/ SQ L Creating a packag e

(2)

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.

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 identi-fiers, 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 exam-ples o f numbers are:

0 3.1415926 1000.0 -100.001 +512

Date s, 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 De clare sec tio n o f yo ur pro c edure. Yo u c an

(3)

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 n-flic t with an Orac le8ikeywo rd may be used.

See the discussion of Oracle8idata 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

(4)

Table 28-1

(continued)

Function Description

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

New_time Converts a Datevalue to the specified tim e zone.

Next_day Returns a Datevalue 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 Numberor Datevalue 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 Datevalue.

To_number Converts the specified value to a num eric value.

Trunc Truncates the specified Dateor Numbervalue 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 claresec tio n, the main b o dy and the Exce ptio nsec tio n. The De clare sec tio n is

(5)

used to dec lare b lo c k-wide variab les. These variab les c an b e used in b etween the Be ginand Endstatements. Yo u may o ptio nally assign an initial value fo r these variab les.

The Be ginstatement 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 Be ginstatement. Pro gram flo w will c o ntinue until it reac hes either the End state-ment o r the Exce ptionstatement. When either o f these statements is reac hed, exe-c utio n is exe-c o mplete and exe-c o ntro l will return to the exe-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 Exce ptionstatement. If the Exce ptionsec tio n isn’t present, an erro r message will be returned to the c all-ing pro gram. Onc e yo u transfer c o ntro l the to Exce ptionsec tio n, yo u c an’t return to the exec utable c o mmands sec tio n.

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:

<< <block_name> >> [Declare

<variable> <datatype> [:= <initial_value>]; [<variable> <datatype> [:= <initial_value>];] ... ]

Begin

<statement>; [<statement>;]... [Exception

When <condition> Then <statement>; [<statement>;]... [When <condition> Then <statement>; [<statement>;]...]... ]

End [ <blo c k_name>] ; where <block_name>is an identifier that is asso c iated with the blo c k; <variable>is an identifier that will be used to sto re info rmatio n lo c ally in the blo c k; .<datatype>is any legal Orac le8idata type; <initial_value>is a c o nstant that is appro priate fo r the data type; <statement>is any legal PL/ SQL statement o r c o mmand; and <condition>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 Othe rs, whic h traps any remain-ing exc eptio ns.

(6)

Table 28-2

Exceptions

Exception Description

CURSOR_ALREADY_OPEN An Openstatem ent tried to open a cursor that w as already open.

DUP_VAL_ON_INDEX An Insertor Updatestatem ent created a duplicate value in a Uniqueindex.

INVALID_CURSOR An Openstatem ent tried to open an undefined cursor; a

Closestatem 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

Connectstatem ent.

NO_DATA_FOUND A Selectstatem 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 Selectstatem 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 (<<) and double greater than (>>) signs, such as <<MyBlock>>. The sam e nam e that begins the block m ust also be specified in the End statem ent, like this:End MyBlock.

(7)

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 Cre ate Packagestatement is explained at the end o f this c hapter.)

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 expres-sion, 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 “Pro-cedures 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 simi-lar 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 [<username>.]<procedure> [(<argument> [,<argument>]...)] {Is|As} <block>

The syntax fo r a func tio n definitio n is:

Function [<username>.]<function> [(<argument> [,<argument>]...)] Return <datatype>

{Is|As} <block>

where <username>is the name o f the user asso c iated with the pro c edure o r func -tio n; <procedure>is the name o f the pro c edure; <function>is the name o f the func tio n;<argument>is <parameter> [In|Out|In Out] <datatype>, where <parameter>is the name o f the parameter; Inmeans that the parameter is passed to the ro utine, but any c hanges in the parameter are no t returned to the c alling

(8)

pro gram, Outmeans that no value is passed to the ro utine, but the ro utine will return a value to the c alling pro gram, In Outmeans 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 <datatype>is the data type asso c iated with the parameter; and

<block>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 Iso r As keywo rds.

Return statement

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

Return(<value>);

where <value>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 ini-tialize 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.

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 tine, loading it, and preparing to run it. All of this w ork is done w hen the first rou-tine 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;

(9)

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 Whileto 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 Ifstatement has the fo llo wing syntax:

If <boolean_expression> {<statement>|<block>} [Elsif <Boolean_expression>

{<statement>|<block>}]... [Else

{<statement>|<block }] End If;

<boolean_expression>is a bo o lean expressio n that is either True o r False. If the Bo o lean expressio n is True, then the statement o r blo c k that immediately fo llo ws the expressio n will be exec uted. Otherwise, the statement o r blo c k that immedi-ately fo llo ws the Elsec lause will be exec uted.

<statement>is an SQL statement o r PL/ SQL c o mmand.

<block>is a PL/ SQL blo c k. While variables and exc eptio ns c an be inc luded, typi-c ally all yo u wo uld use is the Be ginand Endstatements to enc lo se a gro up o f state-ments to be exec uted if <boolean_expression>is True.

Exit statement

The Exitstatement allo ws yo u to exit fro m a lo o p o r fro m a blo c k. Its syntax is:

Exit [<block_name>] [When <boolean_expression>];

<block_name>is the name o f a blo c k ( suc h as, <<myblock>>) . If <block_name> isn’t spec ified, the pro c essing will resume with the statement that immediately fo l-lo ws the next Endstatement. Otherwise, pro c essing will resume with the End state-ment that matc hes the spec ified <block_name>.

(10)

Loop statement

The Loopstatement has the fo llo wing syntax:

Loop

<statement> [<statement>] End Loop;

where <statement>is a valid PL/ SQL statement.

No te that this lo o ping statement c reates an infinite lo o p. The o nly way to leave the lo o p is to use an Exitstatement.

While statement

Whilestatements are c o nstruc ted with the fo llo wing syntax:

While <boolean_expression> Loop

<statement> [<statement>] End Loop;

<boolean_expression>is evaluated at the start o f eac h lo o p. As lo ng as this expressio n is True, the statements c o ntained in the lo o p will be exec uted. If the expressio n is False, exec utio n will resume with the statement after the End Loopstatement.

<statement>is a valid PL/ SQL statement.

For statement

The Forstatement sho uld be familiar if yo u’re a Visual Basic pro grammer. Ho wever, its syntax is a little different than that whic h Mic ro so ft uses:

For <variable> In <start_expression> .. <end_expression> Loop

<statement> [<statement>]... End Loop;

(11)

Unlike the Visual Basic Forstatement, the PL/ SQL Forstatement allo ws yo u to inc rement o nly the Forvariable.

For cursors only:See the section on Cursors later in this chapter to see how to increm ent a cursor.

Cursors

Curso rs are a spec ial type o f variable that allo w yo u to ac c ess the c o ntents o f a Se le ctstatement o ne ro w at a time. Yo u c an mo ve the c urso r thro ugh the result set and perfo rm vario us o peratio ns o n the c o lumns retrieved, inc luding updating val-ues, deleting ro ws, and inserting ro ws.

The Cursor statement

The Cursorstatement defines a c urso r. Its syntax is:

Cursor <cursor>

[Is <select_statement>];

where <cursor>is the name o f the c urso r variable; and<select_statement>is a Se le ctstatement that returns ro ws to be ac c essed thro ugh the c urso r.

Defining a c urso r merely c reates the data struc tures nec essary to ac c ess info rma-tio n fro m the database. No ro ws are ac tually retrieved until the Ope nstatement is exec uted. Ho wever, info rmatio n abo ut the c o lumns retrieved is available and c an be ac c essed by using the %Rowtypeand %Typec urso r attributes.

Cursor attributes

Yo u c an determine additio nal info rmatio n abo ut a c urso r by using a c urso r attribute. Curso r attributes are appended to a c urso r variable, suc h as:

MyCursor%Found

whic h will return a value indic ating whether the last o peratio n that used it was suc -c essful. Yo u -c an use the -c o mbinatio n o f -c urso r and attribute anywhere yo u -c an use a variable.

Table 28-3 lists the attributes available fo r eac h c urso r. No te that yo u need no t do anything to make these attributes available. They are auto matic ally present o nc e a c urso r has been defined.

(12)

Table 28-3

Cursor Attributes

Attribute Description

%Found Is Truew hen the last operation (Select, Insert, Update, or Delete) w as successful.

%Isopen Is Truew hen the cursor is open.

%Notfound Opposite of %Found.

%Row type Returns a record variable containing the sam e structure as the entire row in the table.

%Type Returns the data type of the selected colum n.

The %Rowtypeand %Type attributes are used in the De clare sec tio n as a data type fo r o ther variables. This allo ws yo u to dec lare a variable fo r a c o lumn o r fo r the entire ro w witho ut nec essarily kno wing their data type. Yo u referenc e a partic ular c o lumn by using <rowtype_variable>.<column_name>. Co nsider the fo llo wing c o de fragment:

Declare

Cursor MyCursor Is

Select MyColumn, AnotherColumn From MyTable; MyRow MyCursor%Rowtype;

Begin

Open MyCursor;

If MyRow.MyColumn = 0

/* insert processing statements here */

Else

/* insert processing statements here */

End;

Close MyCursor; End;

MyRow.MyColumnis used to retrieve info rmatio n fro m the MyCo lumn c o lumn fro m the MyTable table in the database.

(13)

Open MyCursor

While MyCursor%Notfound Loop

Fetch MyCursor Into MyVariable;

/* insert processing statements here */

End Loop;

As lo ng as there are ro ws remaining to be fetc hed, this lo o p will pro c ess eac h ro w. If the c urso r didn’t return any ro ws, the pro c essing lo o p wo uld be skipped.

Open statement

Befo re yo u ac c ess a c urso r, yo u must use the Ope nstatement. The syntax fo llo ws:

Open <cursor>;

where <cursor>is the name o f a c urso r that has already been dec lared.

When the Ope nstatement is exec uted, the Se le ctstatement asso c iated with the c urso r is exec uted and the info rmatio n is made available. Yo u c an then use the Fe tchstatement to retrieve the info rmatio n, and the De le teo r Update statements to mo dify the info rmatio n. ( The Fe tchstatement is c o vered later in this c hapter.)

But I did open it:Trying to access a cursor that hasn’t been opened w ill generate an error. Also, trying to open a cursor that is already open w ill generate an error. You can use the %IsOpenattribute to verify that your cursor is in the proper state before trying to use it. This is extrem ely im portant if you are im plem enting code in the Exceptions section and you m ay not know the exact state of the cursor.

Close statement

The Closestatement deallo c ates the reso urc es asso c iated with the c urso r. Its syn-tax is simple:

Close <cursor>;

<cursor>is the name o f a c urso r that has already been dec lared.

Onc e a c urso r has been c lo sed, yo u need to o pen it again befo re yo u c an use it.

Fetch statement

The Fe tchstatement is used to retrieve the next rec o rd into a variable fo r lo c al ac c ess. It has the fo llo wing syntax:

Fetch <cursor> Into {<record>|<variable> [,<variable>]...};

where

(14)

<cursor>is an o pen c urso r; <record>is a variab le dec lared using <cursor> %Ro wtypeas its data type; and<variable>is a variab le who se data type is c o m-patib le with the data type o f the c o rrespo nding c o lumn fro m the c urso r. The list o f variab les must matc h the list o f c o lumns retrieved fro m the c urso r in b o th numb er and data types.

For statement

Ano ther variatio n o f the Forstatement yo u saw earlier in “Flo w Co ntro l” makes it easy to pro c ess all o f the ro ws retrieved fro m the database. Yo u sho uld use the fo l-lo wing syntax:

For <record> In <cursor>

where <record>is a variable dec lared using <cursor>%Rowtype,and <cursor>is an o pen c urso r.

Co nsider the fo llo wing c o de fragment:

Open MyCursor;

For MyRow In MyCursor Loop

/* insert processing statements here */

End Loop;

The statements in the Loopbo dy will be pro c essed fo r eac h ro w retrieved fro m the database. Yo u do n’t need a Fe tchstatement to retrieve the ro w into a variable. The Forstatement handles that fo r yo u auto matic ally. Using the rec o rd variable also sim-plifies yo ur c o de, sinc e yo u do n’t have to wo rry abo ut ensuring that eac h individual c o lumn is spec ified c o rrec tly in the Fe tchstatement.

Update statement

Yo u sho uld use the fo llo wing syntax when updating info rmatio n retrieved by using a c urso r:

Update <table>

Set <column> = <value> [, <column>=<value>] ... Where Current Of <cursor>

(15)

The Updatestatement affec ts o nly the info rmatio n in the c urrent ro w. No o ther ro ws are affec ted when the Whe re Curre nt Ofc urso r c lause is inc luded. No te that in o rder to perfo rm the update, yo u need to ensure that yo ur c urso r ac c esses an updateable view. This means that yo u may o nly ac c ess o ne table at a time when yo u dec lare the c urso r.

Delete statement

Using the De le te statement, yo u c an delete the c urrent ro w po inted to b y the c urso r, with the fo llo wing syntax:

Delete From <table>

Where Current Of <cursor>

where <table>is the name o f the table c o ntaining the ro w yo u want to delete, and <cursor>is an o pen c urso r c o ntaining the info rmatio n yo u want to delete.

Like the Updatestatement, the De le te statement may o nly referenc e a single table and the Whe re Curre nt Ofc lause ensures that o nly the c urrently fetc hed ro w is affec ted by the statement.

Transactions

By no w, yo u understand the impo rtanc e o f using transac tio ns in yo ur applic atio n where yo u need to ensure multiple c hanges are perfo rmed to gether as a single ato mic unit. So it sho uld c o me as no surprise that PL/ SQL also inc ludes suppo rt fo r transac tio n. As yo u wo uld expec t, there is a statement to mark the beginning o f the transac tio n and ano ther statement to mark the end o f the transac tio n.

Set Transaction statement

The Se t Transactionstatement marks the beginning o f a transac tio n and has the fo llo wing syntax:

Set Transaction {Read Only|Use Rollback Segment <segment>}

where <segment>is the name o f a ro llbac k segment that is used by the transac tio n to ho ld undo info rmatio n.

(16)

Savepoint statement

The Save pointstatement allo ws yo u to mark a plac e in yo ur transac tio n where yo u may c ho o se to ro llbac k yo ur wo rk. Its syntax fo llo ws:

Savepoint <savepoint>

where<savepoint>is an identifier that uniquely identifies the savepo int lo c atio n.

Commit statement

The Commit statement saves all o f the database c hanges made to the database sinc e the Se t Transaction statement was exec uted. It has the fo llo wing syntax:

Commit [Work];

The Workkeywo rd is o ptio nal and has no real meaning. It exists so lely to c o mply with the ANSI SQL standard.

Rollback statement

The Rollback statement disc ards all o f the c hanges made by a transac tio n to the database. This statement has the fo llo wing syntax:

Rollback [Work] [To [Savepoint] <savepoint>]

If yo u ro llbac k to the spec ified <savepoint>, all c hanges do ne after the Save point statement are disc arded. All wo rk do ne prio r to the Save pointremains unc o mmit-ted. Yo u must use a Commitstatement to save the c hanges o r a Rollbackstatement witho ut spec ifying a savepo int.

Other useful statements

Besides the statements and c o mmands disc ussed so far, there are a few o thers that yo u may find useful.

DBM S_Output Package

PL/ SQL inc ludes a pac kage to assist yo u with sending o utput to the c o nso le. This pac kage is mo stly useful when debugging yo ur sto red pro c edures using SQL*Plus. The pac kage c o nsists o f three sto red pro c edures with the fo llo wing fo rmat:

DBMS_OUTPUT.PUT (<value>); DBMS_OUTPUT.PUT_LINE (<value>); DBMS_OUTPUT.NEW_LINE;

(17)

The Putro utine displays a single value o n the c o nso le. The o utput c urso r remains o n the same line, so that ano ther c all to Putwill display ano ther value next to the first. The Ne w_Linero utine advanc es the c urso r to the first po sitio n in the next line. Put_Lineis the equivalent o f c alling Put, immediately fo llo wed by Ne w_Line.

These ro utines are c o ntro lled by the SERVEROUTPUT feature that yo u manage with the Se tstatement. Turning On this feature means that the o utput will be sent to the c o nso le, while Offmeans that the o utput will be disc arded.

SET SERVEROUTPUT {ON|OFF}

Setting the Se rve routputfeature o utside yo ur ro utines means that yo u c an leave the debugging c o de in the ro utines. If yo u feel that yo u need to trac e the ro utines exec utio n, yo u c an Se t Se rve routput Onand c all the ro utine in SQL*Plus. If yo u do n’t want to view yo ur debugging c o de, simply Se t Se rve routput Off.

Raise statement

Handling erro rs is always interesting, espec ially when yo u have sto red pro c edures c alling o ther sto red pro c edures. So metimes yo u find an erro r c o nditio n where yo u want to kill the entire transac tio n o r sto red pro c edure. The Raisestatement allo ws yo u to trigger an erro r c o nditio n.

The syntax fo r the Raisestatement is:

Raise [<exception>]

where <exception>is an exc eptio n value selec ted fro m Table 28-2. If a value fo r <exception>is spec ified, the c o de in the c urrent blo c k’s Exc eptio n sec tio n will be triggered. Yo u c an o mit <exception>o nly when yo u are already pro c essing an erro r in the Exc eptio n sec tio n and wish to pass the erro r o nto the Exc eptio n sec tio n o f the blo c k that enc lo ses the c urrent blo c k.

Creating Stored Procedures

(18)

Creating a procedure or function

The Cre ate Proce durestatement is used to c reate a sto red pro c edure, while the Cre ate Functionstatement is used to c reate a sto red func tio n. The syntax fo r these are:

Create [Or Replace]

{<procedure_definition>|<function_definition>}

where <procedure_definition>is the syntax fo r a pro c edure as desc ribed abo ve, beginning with Proce dureand ending with End; and <function_defini-tion>is the syntax fo r a func tio n as desc ribed abo ve, beginning with Functionand ending with End;.

If yo u spec ify the Or Re placec lause, the ro utine will be replac ed with the new ro u-tine in <procedure_definition>o r <function_definition>.

Creating a package

The Cre ate Packagestatement is used to c reate a pac kage. Its syntax is:

Create [Or Replace] Package Body <package> As

[<variable> <datatype> [:= <initial_value>];] ... {<procedure_definition>|<function_definition>} [{<procedure_definition>|<function_definition>}]... [Begin

<statement> [<statement>]... ]

End [<package>];

where <variable>is an identifier that will be used to sto re info rmatio n lo c ally in the blo c k; <datatype>is any legal Orac le8idata type; <initial_value>is a c o n-stant that is appro priate fo r the data type; <procedure_definition>is the syntax fo r a pro c edure as desc ribed abo ve, beginning with Proce dureand ending with End; <function_definition>is the syntax fo r a func tio n as desc ribed abo ve, beginning with Functionand ending with End; and <statement>is any legal PL/ SQL statement o r c o mmand.

A happy ending: The last Endstatem ent in your routine should include the rou-tine’s nam e as the <block_name>, such as End MyProcedure;.This w ill prove extrem ely useful w hen trying to identify the beginning and end of a routine in the package.

(19)

Summary

In this c hapter yo u learned:

✦abo ut the language elements in PL/ SQL language. ✦abo ut the key statements o f the PL/ SQL language. ✦ho w to c reate transac tio ns in PL/ SQL.

✦ho w to c reate sto red pro c edures and func tio ns in PL/ SQL. ✦ho w to c reate pac kages in PL/ SQL.

Thoughts on Oracle8

i

Stored Procedures

I prefer to use three tools to create and test m y stored procedures. I use a tool like Write to actually code the SQL statem ents. Then I use SQL*Plus for DOS to load the statem ents from the file and add them to m y database. I leave the Write session active, so that I can correct syntax errors or add new functions w hile I have the SQL*Plus session. That w ay, all I have to do is save the file and reload it in SQL*Plus.

Once the stored procedure (or function or package) is loaded into m y database, I execute the stored procedure directly in SQL*Plus. This lets m e review the results interactively. I also like to use the DBM S_OUTPUT package to sprinkle m y code w ith debugging statem ents. After all, executing the Set Serveroutput com m and allow s m e to quickly turn the inform a-tion off or on, depending on how bad m y luck is running.

After I’m satisfied that the procedure it doing w hat is should be doing, I create a sim ple Visual Basic program to verify it. Just because m y procedure w orks w ith Oracle’s tools does-n’t m ean that it w ill autom atically w ork w ith Microsoft’s tools. Once the program w orks, I’ll m ove the procedure to m y application and test it over again.

(20)

Gambar

Table 28-1Selected Functions in PL/ SQL
Table 28-1 (continued)
Table 28-2Exceptions
Table 28-3Cursor Attributes

Referensi

Dokumen terkait

You can download and install the soft file of this incredible book Time Mends (Timber Wolves, Book 2) By Tammy Blackwell currently and in the link offered.. Yeah, different with

Indonesia merupakan negara dengan orang muslim terbesar didunia, akan tetapi setiap ormas muslim sendiri tentunya berbeda dalam memutuskan suatu masalah baru yang muncul

54 Tahun 2010 tentang Pengadaan Barang/Jasa Pemerintah serta menindaklanjuti proses seleksi untuk Paket Pekerjaan Pengadaan Meubelair (985 Unit) , bersama ini kami

Additionally, Aaron developed a wide variety of exercises and stretches specific for posture and alignment based on the personal needs and desires of the many clients he has served

n salinannya sebagaimana tertuang dalam lam proses pembuktian kualifikasi

Uang merupakan uang milik masyarakat atau uang beredar di masyarakat (di luar Bank Sentral seperti Bank Indonesia dan perbankan atau semua bank), yang terdiri dari :.. Uang Kertas

Puji syukur kami panjatkan kepada Tuhan Yang Maha Esa atas limpahan rahmat dan hidayah-Nya sehingga Prosiding Seminar Nasional MIPA Universitas Negeri Yogyakarta

As everybody recognizes, book Carr: Five Years Of Rape And Murder By Edna Buchanan is very popular as the window to open up the globe. It implies that reading publication Carr: