Managing transactions provides the user of the Oracle server,the application developer, or the database administrator the capability of guar-anteeing data consistency and data concurrenc
Trang 1The second part of the procedure selects the row where text will be added, locks the rowfor updating, assigns the starting position to the length of the contents + 1 (so no data isoverwritten), and calls the WRITEprocedure This transaction is then committed
Analyzing the Contents of an Internal LOB
In this section, you can analyze the contents of an internal LOBby working with thefunctionsINSTRandSUBSTR Execute the code in Listing 14.8, and make sure that youhave entered SET SERVEROUTPUT ONat the SQL*Plus prompt so you can see output asthe program executes
L ISTING 14.8 Extracting and Matching Data Inside CLOB s
1: DECLARE 2: /* This PL/SQL block finds patterns in a CLOB It also 3: extracts part of the data from a CLOB with SUBSTR */
11: v_Buffer VARCHAR2(100) ; 12: BEGIN
13: Search for 1st Occurrence of Oracle in Row 5 14: SELECT CLOB_LOCATOR into Source_LOB
15: FROM LOBS 16: WHERE LOB_INDEX = 5;
17: v_Position := DBMS_LOB.INSTR(Source_LOB,v_Pattern, 18: v_Starting_Location,v_Nth_Occurrence);
19: DBMS_OUTPUT.PUT_LINE(‘The first occurrence starts at position: ‘ 20: || v_Position);
31: DBMS_OUTPUT.PUT_LINE(‘The second occurrence starts at position: ‘ 32: || v_Position);
33:
34: Extract part of the data from a CLOB
INPUT
continues
Trang 235: SELECT CLOB_LOCATOR into Source_LOB 36: FROM LOBS
The procedure begins by selecting the data from Row 5, and reading the locatorinto the Source_Lobvariable Using the INSTRfunction, the pattern ‘Oracle’,assigned to the v_Patternvariable, is searched for the first occurrence, specified by the
v_Nth_Occurrencevariable The Starting Location is defaulted to the first position in the
CLOB, stored in the v_Starting_Locationvariable The process is repeated, except thatyou are now searching for the second occurrence of ‘Oracle’in the CLOB
The last part of the procedure extracts 11 characters from Row 6, and stores them in
v_Buffer, which is then displayed to the screen
Using TRIM and ERASE to Edit CLOB s
This sections demonstrates the use of the TRIMandERASEprocedures Execute the code
in Listing 14.9
L ISTING 14.9 Reducing Data in CLOB s
1: DECLARE 2: /* This erases the data in Row 6, and trims the data in 3: row 5 to one occurrence of the book title */
12: SELECT CLOB_LOCATOR into Source_LOB 13: FROM LOBS
14: WHERE LOB_INDEX = 6 FOR UPDATE; Locks Row for Update 15: Erase_Amount :=DBMS_LOB.GETLENGTH(Source_LOB);
L ISTING 14.8 continued
OUTPUT
A NALYSIS
INPUT
Trang 3To verify that the ERASEandTRIMprocedures worked, at the SQL prompt type
SELECT * FROM LOBS;
LOB_INDEX CLOB_LOCATOR - -
1 Teach Yourself Oracle8 in 21 Days
2 Oracle Data Warehousing Unleashed
3 Teach Yourself Database Development With Oracle in 21 Days
4 Oracle Unleashed 2E
5 Teach Yourself Oracle8 in 21 Days 6
Three variables are declared:
• Source_Lobholds the locator for the CLOBs you will alter
• Erase_Amountholds the number of bytes to erase from Row 6
• Trim_Amountstores the number of bytes that should remain in Row 5
The procedure starts by reading the locator for the CLOBinto the variable Source_Lob
Erase_Amountis assigned the value of the length of the data in Row 6 by using the
GETLENGTHfunction The ERASEprocedure is called and passes the CLOBlocator, the totalbytes to erase, and the starting position for erasing the data, which is hard-coded to thevalue 1in this example
The second half of the block reduces the data in Row 5 by half The locator for the CLOB
in Row 5 is read into the variable Source_Lob The Amountof data to remain is
calculat-ed by taking the total length of the data by using the GETLENGTHfunction, and dividingthis value by 2 The TRIMprocedure is called, passing the locator and the amount ofbytes to remain The transactions are then committed
INPUT
A NALYSIS
OUTPUT
Trang 4Temporary LOB s
Oracle8i introduced temporary LOBs, which are synonymous with local variables and do
not exist permanently in the database The most common usage of temporary LOBs is forperforming transformations on LOBdata By default their life span is the duration of thesession
One of the biggest advantages of temporary LOBs is their ability to improve performanceover the usage of persistent LOBs By default LOBs are persistent in nature unless other-wise defined This improved performance is gained because there are no redo records oflogging occurring when temporary LOBs are used Likewise, you can explicitly remove atemporaryLOB, thereby freeing up additional memory and tablespace
PL/SQL operates on temporary LOBs through locators in the same way as for persistent
LOBs Because temporary LOBs are never part of any table, you cannot use SQL DataManipulation Language (DML) to operate on them You must manipulated them by usingtheDBMS_LOBpackage as you would with persistent LOBs Security is provided throughtheLOBlocator Only the user who created the temporary LOBcan access it Locators arenot designed to be passed from one user’s session to another
When you copy a persistent LOB into a temporary LOB locator, the temporary
LOB locator points to the persistent LOB The persistent LOB is not copied into the temporary LOB —only the locators are affected.
Note
Managing Temporary LOB s
All temporary LOBs are recorded in the v$temporary_LOBSview A simple selection onthis view will display all temporary LOBs currently valid for that session This is a greatplace to monitor for unwanted overhead of unnecessary temporary LOBs
Creating Temporary LOB s
To create temporary LOBs, you use the procedure CREATETEMPORARY, which resides in the
DBMS_LOBpackage The Syntax for calling this procedure is as follows
Trang 5DBMS_LOB.CREATETEMPORARY (lob_loc, cache, dur);
In this syntax the parameters are as follows:
• lob_locis the location of the LOB
• cachespecifies whether the LOBshould be read into the database buffer
• duris one of two predefined duration values (SESSIONorCALL), which specifieswhether the temporary LOBis cleaned up at the end of the session or call Thedefault value for this parameter is duration
The following example illustrates the creation of a temporary LOB:
begin DBMS_LOB.CREATETEMPORARY (Dest_Loc,
TRUE, DBMS_LOB.SESSION);
End;
In this example a temporary LOBis created that will be loaded into the buffer andremain in existence for the duration of the current session After this session iscompleted, the temporary LOBwill disappear, and all memory and tablespace allocated to
it will be returned
Summary
In this lesson you have learned how Oracle handles large objects, referred to as LOBs Thetwo types of LOBs are internal and external LOBs Internal LOBs can be persistent or tem-porary External LOBs, called BFILEs, are files accessible to the operating system, ratherthan data stored in a table Internal LOBs can also be binary, character, multicharacter, andfixed width These have full transactional support and can be committed or rolled back
LOBs can have a maximum size of 4GB, or the size of an unsigned LONGinteger
Q&A
Q What is the difference between an external and an internal LOB?
A InternalLOBs are stored within the Oracle database External LOBs are stored andmaintained by the operating system
Q What possible uses are there for LOBs?
A You can use LOBs to easily store and track pictures, large text files, and sound files,which can then be used by front-end systems to display or play back the data
Trang 6Q How are paths accessed by Oracle?
A A path is defined as a directory object, which you create by using the SQL
state-mentCREATE DIRECTORY
1 What are the two types of internal LOBs?
2 What is the maximum size of a LOB?
3 Can you write to external files?
4 When copying LOBs from one row to another, is a new locator copied?
Exercise
Create a temporary LOBthat is of BLOBdatatype, that will not be stored in the buffer, andthat will be limited to the current call
Trang 7In Review
You have finished your second week of learning how to gram in PL/SQL The week started with learning about SQL,creating and using tables, and working with stored proceduresand packages You know all about encapsulation and groupingsimilar procedures and functions together in packages Youhave also learned how to plan for and react to certain runtimeerrors that can arise in PL/SQL code This includes how towrite exception-handling routines to handle internal and user-defined PL/SQL processing errors
pro-On Day 9 you learned how to manipulate data with PL/SQLcursors Cursors are wonderful constructs in that they enableyou to process a multiple-row query result set one row at atime You also learned how to pass arguments into cursors andhow to use cursors as variables
You have also, on Day 10, learned about the various PL/SQLcollection types On Day 11, you learned how to use triggers,which are automatically executed in response to certain SQLstatements and database events On Day 12, you were intro-duced to Oracle8i’s object features
On Day 13, you learned how to prepare for errors and writeerror-handling routines to help prevent unwanted termination
of your PL/SQL programs’ execution Finally, the week ended
on Day 14 with you learning how to use the Oracle 8i largeobject datatypes
Trang 9sup-Where You Are Going
Day 15 covers advanced topics such as managing transactionsand locks You will then continue with the topics of dynami-cally creating SQL and writing to external files Next you areexposed to the Oracle-provided package DBMS_JOB Later inthe week, you will see how sessions communicate using the
DBMS_PIPEpackage and learn how to manage alerts by usingtheDBMS_ALERTpackage Toward the end of the week youwill learn about the Java engine, which is a new feature ofOracle 8i You’ll see how Java classes can be loaded into the database, and you’ll learn how you can interface yourPL/SQL code to Java methods Finally, the week ends with adiscussion on how to use Oracle8i’s Advanced Queuing fea-tures
This is your last week reading this book It’s the week withthe toughest and most challenging topics, but they are also themost interesting topics So forge ahead, and good luck!
Trang 11D AY 15
Managing Transactions and Locks
by Tom Luers
Today you will cover transactions and locks, plus the benefits you can gain bycontrolling them Managing transactions provides the user of the Oracle server,the application developer, or the database administrator the capability of guar-anteeing data consistency and data concurrency Data consistency provides theuser a consistent view of data, which consists of data committed by other users
as well as changes made by the user Data concurrency provides the user access
to data concurrently used by many other users Without transactions ing data concurrency and data consistency, the user of the server would experi-ence inconsistent data reads, lost updates, and nonrepeatable reads In today’stransaction and locks lesson you will learn:
coordinat-• Starting and stopping transactions
• Implementing two-phase commits
• Using savepoints
Trang 12Types of Transactions
A transaction is a logical unit of work that is composed of one or more Data
Manipulation Language (DML) or Data Definition Language (DDL) statements.For every transaction in Oracle, two situations can occur If the statements in a transac-tion complete normally, then the effects of the transaction are made permanent in the
database This is called committing the transactions The other situation occurs when any
one of the statements is unable to complete for whatever reason In this case, the effects
of the transaction are removed from the database and the transaction ends This removal
of the effects of a transaction is called rolling back the transaction.
Oracle provides two general types of transactions: read-only and read-write
transactions The read-only transaction specifies that the queried data and all
queries within the same transaction will not be affected by any other transactions thattake place in the database In other words, any subsequent query can only read changes
committed prior to the beginning of the current transaction The read-write transaction
guarantees that data returned by a query is consistent with respect to the time the querybegan
The read-only transaction enforces transaction-level read consistency This type of action can contain only queries and cannot contain any DML statements In this situa-tion, only data committed prior to the start of the transaction is available to the query.Thus, a query can be executed multiple times and return the same results each time.The read-write transaction provides for statement-level read consistency This type oftransaction will never see any of the changes made by transactions that commit duringthe course of a query execution
trans-Starting a Transaction
A transaction begins with the first SQL statement being executed and ends when theeffects of the transaction are saved or backed out The SET TRANSACTIONcommand alsoinitiates a transaction
TheSET TRANSACTIONcommand is an integral part of transaction management Thiscommand performs one of these operations on the current transaction:
• Establishes the transaction as either a read-only or a read-write transaction
• Assigns your current read-write transaction to a specified rollback segment
N EW T ERM
N EW T ERM
Trang 13SET TRANSACTION parameter
In this syntax,parametercan be one of the following values:
• READ ONLY—Establishes transaction-level read consistency
• READ WRITE—Establishes statement-level read consistency
• ISOLATION LEVEL—Establishes how DML transactions are handled You have twooptions here:SERIALIZABLEandREAD COMMITTED The SERIALIZABLEoptions caus-
es any DML transaction to fail if it attempts to manipulate any data object that hasbeen modified and not committed The READ COMMITTEDcauses the same DMLtransaction to wait for the previous DML lock to disappear This is the defaultnature of Oracle
• USE ROLLBACK SEGMENT—Defines the appropriate rollback segment to be used
The read-only transaction is the default mode of all transactions With this mode, you donot have a rollback segment assigned Additionally, you cannot perform an INSERT, a
DELETE, an UPDATE, or a SELECT FOR UPDATEclause command during this transaction
The read-write transaction mode provides no restrictions on the DML statements allowed
in the transaction
TheSET TRANSACTIONcommand allows you to explicitly assign a particular rollbacksegment to the read-write transaction This rollback segment is used to undo any changesmade by the current transaction should a rollback be executed If you do not specify arollback segment, Oracle assigns one to the transaction
The following example of the SET TRANSACTIONcommand would allow the user to runthis script every weekend without worrying about any other users who might be modify-ing data:
Trang 14Committing occurs when the user either explicitly or implicitly saves the transactionchanges to the database permanently Until you perform a commit, the following princi-ples characterize the state of your transaction:
• DML operations affect only the database buffer Because the changes have onlyaffected the buffer, these changes can be backed out
• A rollback segment buffer is created in the server
• The owner of the transaction can view the effects of the transaction by using the
SELECTstatement
• Other users of the database cannot see the effects of the transaction
• The affected rows are locked and other users cannot change the data within theaffected rows
After the commit is executed, the following occurs:
1 Locks held on the affected rows are released
2 The transaction is marked as complete
3 The internal transaction table of the server generates a system change number,assigns this number to the transaction, and saves them both in the table
You use the COMMITstatement to explicitly make permanent the changes from a tion The following example shows a simple transaction being executed, with a COMMIT
transac-being issued after the transaction is executed:
SQL>INSERT INTO TABLE employee VALUES SQL>(emp_id, emp_name)
SQL>VALUES (5, “Jacks Sharon”)
1 row created SQL> COMMIT;
To make an explicit commit by issuing the appropriate commands, you must have the
force transactionsystem privilege To manually commit a distributed transaction thatwas originated by another user, you must have the force any transactionsystem priv-ilege Oracle performs an implicit commit before and after every DDL command Oracledoes this implicit commit automatically without the user having to issue any commands
Trang 15Canceling a Transaction
Rolling back a transaction means undoing any change that the current transaction hasmade To execute a rollback of the entire transaction, you issue the ROLLBACKcommand
The following example illustrates the use of the ROLLBACKcommand to undo the effects
of the UPDATEcommand:
UPDATE TABLE employee (set pay_rate = pay_rate * 1.25 WHERE pay_type = ‘S’;
ROLLBACK;
Alternatively, you can roll back a portion of a transaction by using the ROLLBACK TO SAVEPOINTcommand Savepoints are discussed later in this lesson, in the section
“Creating Bookmarks with Savepoints.”
When you roll back an entire transaction, the following occurs:
1 All changes made by the current transaction are undone, using the correspondingrollback segment
2 All locks on the rows caused by the transaction are released
3 The transaction is ended
When you roll back a transaction to a savepoint, the following occurs:
• Only the SQL statements executed after the last savepoint are rolled back
• The specified savepoint in the ROLLBACKcommand is preserved, but all other points after that savepoint are removed from the database
save-• All locks established since the specified savepoint are released
• The transaction is still active and can continue
No privileges are required to roll back your own transaction Oracle requires that youhave the force transactionsystem privilege to roll back any in-doubt distributed trans-action you own If the distributed transaction is owned by someone else, then you arerequired to have the force any transactionsystem privilege
Oracle performs an implicit rollback if a severe failure occurs with the host computer or
in the application program
Exploring the Two-Phase Commit
Oracle manages the commits and rollbacks of distributed transactions and maintains dataintegrity for all the distributed databases participating in the distributed transaction
Oracle performs these tasks by a mechanism known as two-phase commit.
Trang 16A two-phase commit is a mechanism which guarantees that all database servers
participating in a distributed transaction either all commit or all roll back thestatements in the transaction A two-phase commit mechanism also protects implicitDML operations performed by integrity constraints, remote procedure calls, and triggers
In a nondistributed environment, all transactions are either committed or rolled back as aunit However, in a distributed environment, commits and rollbacks of a distributed trans-action must be coordinated over a network so that the participating databases either allcommit or roll back the transaction This must hold true even if the network fails duringthe distributed transaction The two-phase commit guarantees that the nodes participating
in the transaction either commit or roll back the transaction, thus maintaining completedata integrity of the global database
All implicit DML operations performed by integrity constraints, remote procedure calls,and triggers are protected by Oracle’s two-phase commit
Creating Bookmarks with Savepoints
A savepoint is like a bookmark in the transaction You explicitly place this bookmark forreference at a later time Savepoints are used to break a large transaction up into smallerpieces This allows you to roll back your work to intermediate points in the transactionrather than roll back the entire transaction For example, if you are performing a largenumber of updates and an error occurs, you only have to roll back to the last savepoint;you would not need to reprocess every statement
The following code creates the savepoint named master_credit:
SAVEPOINT master_credit
Savepoint names must be unique within a given transaction If you create a second point named the same as an earlier savepoint, the previous savepoint is erased
save-The following is an example of rolling back a transaction to the employee_1savepoint:
INSERT INTO employee VALUES (6,’Tom Brandon’,3,1000.00,’S’);
SAVEPOINT employee_1;
INSERT INTO employee VALUES (7,’Catherine Ann’,2,2000.00,’S’);
ROLLBACK TO SAVEPOINT employee_1;
In this example, the insertion of the employee Catherine Ann is removed fromthe transaction At the point of the rollback to the savepoint, the insertion of Tom
is the pending data in the current transaction
INPUT
N EW T ERM
A NALYSIS
Trang 17Using Release Option
Typically when your program ends successfully, all locks, cursors, and some memory arereleased back to the system However, if your program terminates abnormally, some ofthese locks and cursors might remain active for a period of time This causes unwantedoverhead in the database, until the database recognizes the termination and then cleans
In this example, you are forcing the program to terminate cleanly This causesthe locks, memory, and cursors to be freed up Without the release option, youmay incur some unwanted overhead in the database for a short period of time
Using Locking
The Oracle database uses locks to give the user temporary ownership and control of adata object such as a table or row Oracle automatically locks a row on behalf of a trans-action to prevent other transactions from acquiring a lock on the same row You don’twant simultaneous row manipulations by two separate transactions Data locks preventdestructive interference of simultaneous conflicting DDL and DML statements Forexample, Oracle prevents a table from being dropped if there are uncommitted transac-tions on that table These data locks are automatically released when the transactioncompletes by a commit or rollback
Oracle generates what’s known as a read-consistent view of data when you query data
and while at the same time the data is being manipulated by another user When a query
is active, the results of the query do not change, regardless of any update manipulationsthat occur If the query is reexecuted, the data returned reflects any updates executed Thenext two sections examine two types of data locking: table and row
Locking Tables
DML operations can obtain data locks for specific rows and for specific tables Theselocks are used to protect the data in the table when the table is being accessed concur-rently by multiple users
INPUT
A NALYSIS
Trang 18A transaction acquires a table lock when a table is modified by the following DML ments:INSERT,UPDATE,DELETE,SELECTwith the UPDATEoption, and LOCK TABLE Thetable lock is specifically in place to ensure that the current transaction has access to thedata and to prevent any conflicting DDL operations that might happen.
state-Note that placing a table lock does prevent other transactions acquiring a lock (row or table) on the same table.
Note
The table lock can be executed in five different modes:
• row share—This table lock is the least restrictive of the table locks It allows forother concurrent transactions to query, insert, update, delete, and lock rows in thesame table The row sharetable lock does not allow exclusive write access to thesame table
• row exclusive—This lock occurs when several rows in a table have been updated.This lock still allows other transactions to query, insert, update, delete, or lock rows
in the same table The row exclusivelock does not prevent any manual locking orexclusive read and writes on the same table
• share lock—Theshare locktable lock allows for other transactions to onlyquery and lock specific rows This lock prevents all updates, inserts, and deletesfrom the same table
• share row exclusive—This table lock is accomplished only through the locktable with the share row exclusiveparameter This lock only permits queries andselects for UPDATEstatements
• exclusive—This lock allows the transaction write access to a table This lockmeans that other transactions can only query the table
Implicit data locking occurs automatically for all SQL statements, so users of the base do not have to explicitly lock any rows By default, Oracle locks resources at thelowest level possible
data-In a multiuser database, locks have two different levels:
• exclusive—This prohibits the sharing of the associated resource The first tion that acquires the resource is the only transaction that can alter the resourceuntil the lock is released
transac-• share—This lock allows the associated resource to be shared, depending on theoperations involved Several transactions can acquire share locks on the same
Trang 19Locking Rows
Row locks are acquired automatically by the transactions when a row is modified by thefollowing commands:INSERT,DELETE,UPDATE, and SELECTwith the FOR UPDATEclause
The following example of the SELECTcommand places a row lock on the employeetable:
SELECT emp_id, pay_rate FROM employee
WHERE pay_type = ‘H’
FOR UPDATE;
These row locks stay in effect until the transaction is completed or rolled back
The row lock is always exclusive, which prohibits other transactions from fying the same row When the row lock is issued, a corresponding table lock is alsoissued to prevent any conflicting DDL statements from taking effect
modi-Explicit Locks
A transaction explicitly acquires the specified table locks when a LOCK TABLEstatement
is executed and overrides the default locking mechanisms When a LOCK TABLEstatement
is issued on a view, the underlying base tables are locked The syntax for the LOCK TABLE
statement is as follows
LOCK TABLE table_name IN lock_mode MODE NOWAITE;
In this syntax the parameters are as follows:
• table_nameis the name of the table you want to lock
• lock_modeis the mode you want See a full listing of the lock modes earlier in thislesson, in the section called “Locking Tables.”
• NOWAITis optional If it is specified, then control is immediately returned to thetransaction if there is already a lock on the data object If NOWAITis omitted, thenthe transaction waits for the existing lock to be lifted, and then locks the dataobject for itself and executes the transaction
The following example illustrates the use of the LOCK TABLEstatement:
LOCK TABLE employee, department
Trang 20The DBMS_LOCK Package
Oracle supplies a package with the database to assist you in managing the databaselocks This Oracle-supplied package is named DBMS_LOCK Through this package, you canrequest a lock of a specific mode, give it a unique name recognizable in another proce-dure in the same or another instance, change the lock mode, and release the lock.The following functions are included in the DBMS_LOCKpackage:ALLOCATE_UNIQUE,
REQUEST,CONVERT,RELEASE, and SLEEP They are described in more detail in the ing sections
follow-TheALLOCATE UNIQUE Function
TheALLOCATE_UNIQUEfunction allocates a unique lock identifier (in the range of
1073741824 to 1999999999), given a lock name Lock identifiers are used to enableapplications to coordinate their use of locks The ALLOCATE UNIQUEfunction is providedbecause in some cases it might be easier for applications to coordinate their use of locksbased on lock names rather than lock numbers
If you choose to identify locks by name, you can use ALLOCATE_UNIQUEto generate aunique lock identification number for these named locks
The first session to call ALLOCATE_UNIQUEwith a new lock name causes a unique lock ID
to be generated and stored in the DBMS_LOCK_ALLOCATEDtable Subsequent calls (usually
by other sessions) return the lock ID previously generated The syntax for the
ALLOCATE_UNIQUEfunction is as follows
DBMS_LOCK.ALLOCATE_UNIQUE ( lockname IN VARCHAR2, lockhandle OUT VARCHAR2, expiration_secs IN INTEGER DEFAULT 864000);
In this syntax the parameters are as follows:
• locknameis the name of the lock for which you want to generate a unique ID
• lockhandlereturns the lock identifier for the unique identifier generated by theprocedure
• expiration secsis the number of seconds to wait after the last ALLOCATE_UNIQUE
has been performed on a given lock, before permitting that lock to be deleted fromtheDBMS_LOCK_ALLOCATEDtable
Exploring the REQUESTFunction
TheREQUESTfunction, as the name implies, requests a lock with a given mode The tax for the REQUESTfunction is as follows
Trang 21DBMS_LOCK.REQUEST(
id IN INTEGER ||
lockhandle IN VARCHAR2, lockmode IN INTEGER DEFAULT X_MODE, timeout IN INTEGER DEFAULT MAXWAIT, release_on_commit IN BOOLEAN DEFAULT FALSE, RETURN INTEGER;
In this syntax the parameters are as follows:
• idis the user assigned lock identifier or the lockhandlereturned by the
4 You already own the specified lock id or handle
TheCONVERT Function
TheCONVERTfunction converts a lock from one mode to another mode The followingdisplays the syntax for the CONVERTfunction
Trang 22id IN INTEGER ||
lockhandle IN VARCHAR2, lockmode IN INTEGER, timeout IN NUMBER DEFAULT MAXWAIT) RETURN INTEGER;
In this syntax the parameters are as follows:
• idis the user-assigned lock identifier or the lockhandlereturned by the
4 You do not own the specified lock
TheRELEASE Function
TheRELEASEfunction is used to release a lock that was explicitly acquired via the
Trang 23TheSLEEP Function
This procedure will suspend the current session for a specified period of time
DBMS_LOCK.SLEEP ( seconds IN NUMBER);
In this syntax secondsis the number of seconds the session will be suspended
Using Other Locks
Oracle provides a variety of other minor locks I call them minor not because of theirimportance, but because most users don’t generally interact with them directly The fol-lowing are the most common minor locks:
• Dictionary locks are used to protect the database objects from changing during a
transaction This type of lock is automatically acquired by Oracle when a DDLstatement requires it Like the locks mentioned in the previous section, the dictio-nary lock can be either exclusive or shared
• Internal locks protect the internal components of the database and memory These
components are inaccessible by end users For example, locks can be placed on logfiles, control files, data dictionary cache files, and archive files
• Distributed locks ensure data consistency across multiple instances Oracle
auto-matically creates these locks as needed
Monitoring Locks
Oracle provides several ways to monitor what locks are in place within the database Forexample, examining the V$LOCKdatabase view will list information about a lock, such asthe system ID of the process holding the lock and the type of lock held Additionally, the
DBA_DDL_LOCKS,DBA_DML_LOCKS, and DBA_LOCKStables display similar data about locks
Likewise, you can use the Oracle tool SQL*DBA In SQL*DBA, the Lock Monitorscreen gives similar information from the V$Lockdatabase view
Trang 24Transactions are logical groups of SQL statements that begin when the statements areexecuted and end with either a commit or rollback Transactions provide database usersthe guarantee of data concurrency and data consistency This guarantee holds true for dis-tributed and nondistributed databases Locks provide a means to ensure data integrity andconcurrence when data manipulations occur
Q&A
Q Why do DML statements need to be committed?
A Committing a DML statement accomplishes several things: The transaction is
ended, which in turn releases any locks the transaction might have created
Q Do I have to roll back an entire transaction if something does not process completely?
A The rollback can be issued to remove all effects of the current transaction.
Additionally, you can roll back to an intermediate point in the transaction known as
a savepoint
Q What are the two types of transactions?
A The two main types of transactions are read-only and read-write transactions.
1 How is a transaction ended?
2 What is the difference between row locking and table locking?
3 What is the purpose of a savepoint?
4 What is the purpose of the two-phase commit?
5 What is the typical return value when the DBMS_LOCKfunction ran successfully?
Exercise
Write a PL/SQL block that establishes a savepoint, inserts a single record into the
employeetable, commits the data if the new record does not replicate an existing record,
Trang 25D AY 16
Generating Dynamic SQL
by Timothy Atwood and Jonathan Gennick
Dynamic SQL is SQL, or PL/SQL, that is generated by a program when theprogram runs You use dynamic SQL when you need to write generic software.For example, if you were developing a report generator, you wouldn’t knowahead of time the reports that people would develop using that generator Youwould need to make your code flexible and generic enough to allow users toexecute any query they might want You obviously can’t do that by hard-codingSQL statements in your code Your code would need to build the SQL state-ments on the fly
Today you will learn how to do the following:
• Use Oracle’s built-in DBMS_SQLpackage to execute dynamic SQL
• Use the new native dynamic SQL feature in Oracle8i