transaction and sql

Upload: lakhveer-kaur

Post on 08-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Transaction and SQL

    1/35

    Transaction A sequence of many actions which are considered to beone atomic unit of work.

    Read, write, commit, abort Governed by four ACID properties: Atomicity, Consistency, Isolation, Durability Has a unique starting point, some actions and one endpoint DBMS actions: reads, writes

    Special actions: commit, abort For now, assume reads and writes are on tuples; A transaction is a unit of work which completes as a unitor fails as a unit.The ACID Properties Atomicity: All actions in the transaction happen, or nonehappen.

    Consistency: If each transaction is consistent, and theDB starts consistent, it ends up consistent. Isolation: Execution of one transaction is isolated fromthat of other transactions. Durability: If a transaction commits, its effectspersist. A transaction is a collection of operations involving dataitems in a database. Read, insert, delete, and update areexample operations. There are four important propertiesof transactions that a DBMS must ensure to maintaindata in the face of concurrent access and systemfailures:

  • 8/7/2019 Transaction and SQL

    2/35

    Atomicity: Users should be able to regard theexecution of each transaction as atomic: either allactions are executed or none are executed. Users should

    not have to worry about the effect of incompletetransactions (example, when a system crash occurs). Consistency: Each transaction, run by itself with noconcurrent execution of other transactions, mustpreserve the consistency of the database. This propertyis called consistency. Ensuring this property of thetransaction is the responsibility of the user.

    Isolation: Users should be able to understand thetransaction without considering the effect of otherconcurrently executing transactions, even if the DBMSinterleaves the actions of several transactions.Transactions are isolated, or protected, from theeffects of concurrently scheduling other transactions. Durability: Once the DBMS informs the user that a

    transaction has been successfully completed, its effectsshould persist even if the system crashes before all itschanges are reflected on disk. Passing the ACID TestConcurrency Control Guarantees Consistency andIsolation, given Atomicity.Logging and Recovery Guarantees Atomicity andDurability. AtomicityAll-or-nothing, no partial results. An event eitherhappens and is committed or fails and is rolled back. e.g. in a money transfer, debit one account, credit the

  • 8/7/2019 Transaction and SQL

    3/35

    other. Either both debiting and crediting operationssucceed, or neither of them do. Transaction failure is called Abort

    Commit and abort are irrevocable actions. There is noundo for these actions. An Abort undoes operations that have already beenexecuted For database operations, restore the datas previousvalue from before the transaction (Rollback-it); aRollback command will undo all actions taken since the

    last commit for that user. But some real world operations are not undoable.Examples - transfer money, print ticket, fire missile Consistency Every transaction should maintain DB consistency Referential integrity - e.g. each order references anexisting customer number and existing part numbers

    The books balance (debits = credits, assets = liabilities) Consistency preservation is a property of a transaction,not of the database mechanisms for controlling it (unlikethe A, I, and D of ACID) If each transaction maintains consistency, then a serialexecution of transactions does also A database state consists of the complete set of datavalues in the database A database state is consistent if the database obeys allthe integrity constraint A transaction brings the database from one consistentstate to another consistent state

  • 8/7/2019 Transaction and SQL

    4/35

    Consistent state diagram IsolationIntuitively, the effect of a set of transactions should be

    the same as if they ran independently. Formally, an interleaved execution of transactions isserializable if its effect is equivalent to a serial one. Implies a user view where the system runs each userstransaction stand-alone. Of course, transactions in fact run with lots ofconcurrency, to use device parallelism this will be

    covered later. Transactions can use common data (shared data) They can use the same data processing mechanisms(time sharing)Durability When a transaction commits, its results will survivefailures (e.g. of the application, OS, DB system even of

    the disk). Makes it possible for a transaction to be a legalcontract. Implementation is usually via a log DB system writes all transaction updates to a log file to commit, it adds a record commit(Ti) to the log When the commit record is on disk, the transaction iscommitted. system waits for disk ack before acknowledging to user Active: transaction is started and is issuing reads andwrites to the database Partially committed: operations are done and values are

  • 8/7/2019 Transaction and SQL

    5/35

    ready to be written to the database Committed: writing to the database is permitted andsuccessfully completed

    Abort: the transaction or the system detects a fatalerror Terminated: transaction leaves the system A transaction reaches its commit point when alloperations accessing the database are completed and theresult has been recorded in the log. It then writes a[commit, ] and terminates

    When a system failure occurs, search the log file forentries [start, ]and if there are no logged entries [commit, ]then undo alloperations that have logged entries [write, , X, old_value,new_value]Why is Concurrency Control Needed? Several problems occur when concurrent transactions

    execute in an uncontrolled manner A schedule of concurrent transactions is a particularsequence of interleaving of their read or write operations In general a transaction, has a set of data items itaccesses (read set), and a set of data items it modifies(write set)Lost Update Problem - Successfully completed update isoverridden by another user. What should the final Order Value be? Which Update has been lost? Loss of T2s update avoided by preventing T1 fromreading balx until after update.

  • 8/7/2019 Transaction and SQL

    6/35

  • 8/7/2019 Transaction and SQL

    7/35

    T1 T2R(A)W(A)

    R(B)W(B)R(C)W(C) In a complete schedule, each transaction ends in commitor abort.Initial State + Schedule Final State

    Serial schedule is a schedule in which all the operationsof one transaction are completed before anothertransaction can begin (that is, there is no interleaving). One sensible isolated, consistent schedule: Run transactions one at a time, in a series.NOTE: Different serial schedules can have differentfinal states; all are OK

    -- DBMS makes no guarantees about the order in whichconcurrently submitted transactions are executed. Serializable Schedule A schedule whose effect on the DB state is the sameas that of some serial schedule All serial schedules are serializable. But the reversemay not be true Let T be a set of n transactions . If the n transactionsare executed serially (call this execution S), we assumethey terminate properly and leave the database in aconsistent state. A concurrent execution of the ntransactions in T (call this execution C) is called

  • 8/7/2019 Transaction and SQL

    8/35

    serializable if the execution is computationally equivalentto a serial execution. There may be more than one suchserial execution. That is, the concurrent execution C

    always produces exactly the same effect on the databaseas some serial execution S does. (Note that S is someserial execution of T, not necessarily the order). A serialschedule is always correct since we assume transactionsdo not depend on each other and furthermore, weassume, that each transaction when run in isolationtransforms a consistent database into a new consistent

    state and therefore a set of transactions executed oneat a time (i.e. serially) must also be correct. Final state is what some serial schedule would haveproduced. Aborted Xacts are not part of schedule; ignore themfor now (they are made to `disappear by using logging).In general, serializability is a good property But

    difficult to achieve due to lack of effective algorithms. Serializability Objective of a concurrency control protocol is toschedule transactions in such a way as to avoid anyinterference. Could run transactions serially, but this limits degree ofconcurrency or parallelism in system. Serializability identifies those executions oftransactions guaranteed to ensure consistency.ScheduleSequence of reads/writes by set of concurrenttransactions.

  • 8/7/2019 Transaction and SQL

    9/35

    Serial ScheduleSchedule where operations of each transaction areexecuted consecutively without any interleaved

    operations from other transactions.Nonserial Schedule Schedule where operations from set of concurrenttransactions are interleaved. Objective of serializability is to find nonserialschedules that allow transactions to executeconcurrently without interfering with one another.

    In other words, want to find nonserial schedules thatare equivalent to some serial schedule. Such a schedule iscalled serializable.In serializability, ordering of read/writes is important:(a) If two transactions only read a data item, they do notconflict and order is not important.(b) If two transactions either read or write completely

    separate data items, they do not conflict and order is notimportant.(c) If one transaction writes a data item and anotherreads or writes same data item, order of execution isimportant. Serializability Violations Two transactions T1 and T2 are said to conflict if someaction t1 of T1 and an action t2 of T2 access the sameobject and at least one of the actions is a write. Theconflict is called a RW-conflict if the write set of onetransaction intersects with the read set of another. AWW-conflict occurs if the conflict is between two

  • 8/7/2019 Transaction and SQL

    10/35

  • 8/7/2019 Transaction and SQL

    11/35

    Abort of T1 requires abort of T2! Cascading Abort What about WW conflicts & aborts? T2 overwrites a value that T1 writes.

    T1 aborts: its remembered values are restored. Lose T2s write! We will see how to solve this, too. Recoverable ScheduleA schedule where, for each pair of transactions Ti andTj, if Tj reads a data item previously written by Ti, thenthe commit operation of Ti precedes the commitoperation of Tj.

    Unrecoverable ScheduleT1 T2R(A)W(A)R(A)W(A)commit

    abortRecoverable ScheduleT1 T2R(A)W(A)R(A)W(A)commitcommitAbort of T1 in first figure requires abort of T2! But T2 has already committed and hence cannot undoits actions! This is unrecoverable schedule. A recoverable

  • 8/7/2019 Transaction and SQL

    12/35

    schedule is one in which this cannot happen. i. e. a transaction commits only after all thetransactions it depends on (i. e. it reads from or

    overwrites) commit.An ACA (avoids cascading abort) schedule is one in whichcascading abort cannot arise. A transaction only reads/ writes data from committedtransactions. Recoverable implies ACA (but not vice- versa!). Realsystems typically ensure that only recoverable schedules

    arise (through locking). Concurrency Control Techniques Two basic concurrency control techniques: Locking, Timestamping. Both are conservative approaches: delay transactions incase they conflict with other transactions. Optimistic

    methods assume conflict is rare and only check forconflicts at commit. LockingThe concept of locking data items is one of the maintechniques for controlling the concurrent execution oftransactions. A lock is a variable associated with a data item in thedatabase. Generally there is a lock for each data item in thedatabase. A lock describes the status of the data item withrespect to possible operations that can be applied to that

  • 8/7/2019 Transaction and SQL

    13/35

    item used for synchronising the access by concurrenttransactions to the database items.

    A transaction locks an object before using it When an object is locked by another transaction, therequesting transaction must wait Binary locks have two possible states: 1.locked (lock_item (X) operation) and 2.unlocked (unlock (X) operation Multiple-mode locks allow concurrent access to the

    same item by several transactions. Three possible states:

    1.read locked or shared locked (other transactions areallowed to read the item) 2.write locked or exclusive locked (a single transactionexclusively holds the lock on the item) and 3.unlocked.

    Locks are held in a lock table. upgrade lock: read lock to write lock downgrade lock: write lock to read lock

    TYPES OF LOCKS SHARED LOCKS EXCLUSIVE LOCKSTransaction uses locks to deny access to othertransactions and so prevent incorrect updates. Most widely used approach to ensure serializability. Generally, a transaction must claim a shared (read) orexclusive (write) lock on a data item before read or

  • 8/7/2019 Transaction and SQL

    14/35

    write. Lock prevents another transaction from modifying itemor even reading it, in the case of a write lock.

    Locking - Basic Rules If transaction has shared lock on item, can read but notupdate item. If transaction has exclusive lock on item, can both readand update item. Reads cannot conflict, so more than one transaction canhold shared locks simultaneously on same item.

    Exclusive lock gives transaction exclusive access to thatitem. Some systems allow transaction to upgrade read lock toan exclusive lock, or downgrade exclusive lock to a sharedlock. Two-Phase Locking (2PL)Strict 2PL:

    If T wants to read an object, first obtains an S lock. If T wants to modify an object, first obtains X lock. Hold all locks until end of transaction. Guarantees serializability, and recoverable schedule,too! also avoids WW problems!2PL: Slight variant of strict 2PL transactions can release locks before the end (commitor abort)? But after releasing any lock it can acquire no new locks Guarantees serializabilityA two-phase locking ( 2PL) scheme is a locking scheme in

  • 8/7/2019 Transaction and SQL

    15/35

    which a transaction cannot request a new lock afterreleasing a lock. Two phase locking therefore involves twophases:

    Growing Phase ( Locking Phase) - When locks areacquired and none released. Shrinking Phase ( Unlocking Phase) - When locks arereleased and none acquired.The attraction of the two-phase algorithm derives from atheorem which proves that the two-phase lockingalgorithm always leads to serializable schedules. This is a

    sufficient condition for serializability although it is notnecessary.Strict two-phase locking ( Strict 2PL) is the most widelyused locking protocol, and has following two rules: If a transaction wants to read (respectively, modify) anobject, it first requests a shared (respectively,exclusive) lock on the object.

    All locks held by a transaction are released when thetransaction is completedIn effect the locking protocol allows only safeinterleavings of transactions.Q) Three transactions A, B and C arrive in the timesequence A, then B and then C. The transactions are runconcurrently on the database. Can we predict what theresult would be if 2PL is used? No, we cannot do that since we are not able to predictwhich serial schedule the 2PL schedule is going to beequivalent to. The 2PL schedule could be equivalent to anyof the following six serial schedules: ABC, ACB, BAC,

  • 8/7/2019 Transaction and SQL

    16/35

    BCA, CAB, CBA. Two-Phase Locking (2PL)Transaction follows 2PL protocol if all locking operations

    precede first unlock operation in the transaction. Two phases for transaction: Growing phase - acquires all locks but cannot releaseany locks. Shrinking phase - releases locks but cannot acquire anynew locks. Preventing Lost Update Problem using 2PL Eg in slides

    Preventing Uncommitted Dependency Problem using 2PL Locking GranularityA database item which can be locked could be a database record a field value of a database record the whole database Trade-offs

    ?coarse granularity - the larger the data item size, thelower the degree of concurrency?fine granularity - the smaller the data item size, themore locks to be managed and stored, and the morelock/unlock operations needed.DeadlockAn impasse that may result when two (or more)transactions are each waiting for locks held by the otherto be released. Eg in slides Conditions For Deadlock Mutual Exclusion Hold And Wait

  • 8/7/2019 Transaction and SQL

    17/35

    Non Preemption Circular WaitRecovery

    Occurs in case of transaction failures. Database (DB) is restored to the most recentconsistent state just before the time of failure. To do this, the DB system needs information aboutchanges applied by various transactions. It is the systemlog.Contents of System Log:

    [start_transaction, T]: Indicates that transaction T hasstarted execution. [write_item, T, X, old_value, new_value]: Indicates thattransaction T has changed the value of DB item X fromold_value to new_value. [read_item, T, X]: Indicates that transaction T hasread the value of DB item X.

    [commit, T]: Indicates that transaction T has completedsuccessfully, and affirms that its effect can becommitted (recorded permenantly) to the database. [abort, T]: Indicates that transaction T has beenaborted.Deadlock Only one way to break deadlock: abort one or more ofthe transactions. Deadlock should be transparent to user, so DBMSshould restart transaction(s). Three general techniques for handling deadlock: Timeouts.

  • 8/7/2019 Transaction and SQL

    18/35

    Deadlock prevention. Deadlock detection and recovery.Timeouts

    Transaction that requests lock will only wait for asystem-defined period of time. If lock has not been granted within this period, lockrequest times out. In this case, DBMS assumes transaction may bedeadlocked, even though it may not be, and it aborts andautomatically restarts the transaction.

    Deadlock Prevention DBMS looks ahead to see if transaction would causedeadlock and never allows deadlock to occur. Could order transactions using transaction timestamps: Wait-Die - only an older transaction can wait foryounger one, otherwise transaction is aborted (dies) andrestarted with same timestamp.

    Wound-Wait - only a younger transaction can wait foran older one. If older transaction requests lock held byyounger one, younger one is aborted (wounded).Deadlock Detection and Recovery DBMS allows deadlock to occur but recognizes it andbreaks it. Usually handled by construction of wait-for graph(WFG) showing transaction dependencies: Create a node for each transaction. Create edge Ti -> Tj, if Ti waiting to lock item locked byTj. Deadlock exists if and only if WFG contains cycle.

  • 8/7/2019 Transaction and SQL

    19/35

    WFG is created at regular intervals. Recovery Outline Restore to most recent consistent state just before

    time of failure Use data in the log file Catastrophic Failure Restore database from backup Replay transactions from log file Database becomes inconsistent (non-catastrophicerrors)

    Undo or Redo last transactions until consistent state isrestoredRecovery Algorithms for Non-catastrophic Errors:Deferred Update (NO-UNDO/REDO): Data written to buffers Not physically updated until after commit point reachedand logs have been updated

    No undo is even necessary Redo might be necessary on transactions that havebeen logged but not physically updated Known as the NO-UNDO/REDO algorithmImmediate Update (UNDO/REDO): Database being updated as transaction occurs However, log always force written first Partially completed transactions will have to be undone Committed transactions might have to be redone Known as the UNDO/REDO algorithm Variation on the scheme: Data is physically updated before commit

  • 8/7/2019 Transaction and SQL

    20/35

    Only requires UNDO Known as the UNDO/NO-REDO algorithm Logging

    Record REDO and UNDO information, for every update,in a log. Sequential writes to log (put it on a separate disk). Minimal info (diff) written to log, so multiple updatesfit in a single log page.Log: An ordered list of REDO/ UNDO actions Log record contains:

    and additional control infoCaching of Disk Blocks: Disk blocks typically cached to main memory Changes made to cache block which is then written backat some later time Many DBMSs even handle the low-level I/ODBMS Caching:

    All database accesses check to see if required item isin the cache first. If not, item is loaded into cache Dirty bit: Determines if cache block has been updatedand needs to be written back to disk Pin/Unpin bit: Is it OK to write block back to disk yet? In-place updating: Block is written back out to samelocation. Overwrite original Shadowing: Block is written to new location? Old copy is kept? Before Image (BFIM) & After Image (AFIM) The Write- Ahead Logging Protocol: Must force the log record for an update before the

  • 8/7/2019 Transaction and SQL

    21/35

    corresponding data page gets to disk. Must write all log records for a transaction beforecommit

    The rule that all transactions follow in the WALprotocol is "Write the log before you write the data.When a transaction wants to update a record, it pins thepage containing the record in the main-memory bufferpool, modifies the page in memory, generates anundo/redo record, forces the undo/redo record to thelog, and unpins the page in the buffer pool. At some later

    time, the page replacement algorithm or a checkpoint willwrite the page back to the database. WAL protocol: #1 guarantees Atomicity. #2 guarantees Durability. Each log record has a unique Log Sequence Number(LSN). LSNs always increasing.

    Each data page contains a pageLSN. The LSN of themost recent log record for an update to that page. System keeps track of flushedLSN. The max LSNflushed so far. WAL: Before a page is written, pageLSN

  • 8/7/2019 Transaction and SQL

    22/35

    Checkpoints in the System Log Checkpoint record written in log when all updated DBbuffers written out to disk

    Any committed transaction occurring before checkpointin log can be considered permanent (wont have to beredone after crash) Actions suspend execution of all transactions force-write all modified buffers to disk write checkpoint entry in log and force write log

    resume transactions Checkpointing: Periodically, the DBMS creates acheckpoint, in order to minimize the time taken torecover in the event of a system crash. It quiesces thesystem (makes all currently executing transactionspause), writes all dirty buffers to disk, and then allowstransactions to resume normal processing.

    The problem with this simple checkpoint is that itmakes the data unavailable for too long, possibly severalminutes, while the checkpoint is being done. There isanother technique called Fuzzy checkpoint, which doesnot have this problem, because it does not quiesce thesystem. Instead, for each buffer, the fuzzy checkpointprocedure latches the buffer (gets an exclusivesemaphore on it), writes it to disk if it is dirty, and thenunlatches the buffer. In addition, fuzzy checkpointwrites the IDs of the currently active transactions tothe log. Fuzzy checkpoint just locks buffers one at a timeand releases them.

  • 8/7/2019 Transaction and SQL

    23/35

    How does the system recovers from a crash: The crashrecovery algorithm reads the most recent checkpointinformation from the log, which yields a set of

    transaction IDs that were active at the time of thecheckpoint. Then it scans the log forward from thecheckpoint, reapplying every undo/redo record to thedatabase (this is called REDO ALL). During the forwardpass, it analyzes the log to determine which transactionsdid not commit or abort before the crash. Thesetransactions are called the "losers." Then, the recovery

    algorithm scans the log in reverse, undoing log recordsfor all the losers (this is called UNDO LOSERS). Additional Crash Issues: What happens if systemcrashes during Analysis? During REDO? How do you limitthe amount of work in REDO ? Flush asynchronously in the background. Watch hot spots!

    How do you limit the amount of work in UNDO ? Avoid long- running transactions.

  • 8/7/2019 Transaction and SQL

    24/35

    Introduction

    PL/SQL is a database-oriented programming language

    that extends Oracle SQL with procedural capabilities.We will review in this lab the fundamental features ofthe language and learn how to integrate it with SQL tohelp solve database problems.

    Need for PL/SQL

    SQL statements are defined in term of constraints wewish to fix on the result of a query. Such a language iscommonly referred to as declarative. This contrasts withthe so called procedural languages where a programspecifies a list of operations to be performedsequentially to achieve the desired result. PL/SQL addsselective(i.e. if...then...else...) and iterativeconstructs

    (i.e. loops) to SQL.PL/SQL is most useful to write triggersand storedprocedures. Stored procedures are units of proceduralcode stored in a compiled form within the database.

    PL/SQL Fundamentals

    PL/SQL programs are organised in functions, procedures

    and packages (somewhat similar to Java packages). Thereis a limited support for object-oriented programming.PL/SQL is based on the Ada programming language, andas such it shares many elements of its syntax with Pascal.

  • 8/7/2019 Transaction and SQL

    25/35

    Your first example in PL/SQL will be an anonymousblockthat is a short program that is ran once, but thatis neither named nor stored persistently in the database.

    SQL> SET SERVEROUTPUT ON

    SQL> BEGIN

    2 dbms_output.put_line('Welcome to PL/SQL');

    3 END;

    4 /

    SET SERVEROUTPUT ON is the SQL*Plus command1

    to activate the console output. You only need to issue

    this command once in a SQL*Plus session. the keywords BEGIN...END define a scopeand areequivalent to the curly braces in Java {...} a semi-column character (;) marks the end of astatement the put_line function (in the built-in packagedbms_output) displays a string in the SQL*Plus console.

    You are referred to Table 2 for a list of operators, andto Table 3 for some useful built-in functions.

    Compiling your code.

    http://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#foot31http://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#tbl:opshttp://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#tbl:funchttp://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#foot31http://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#tbl:opshttp://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#tbl:func
  • 8/7/2019 Transaction and SQL

    26/35

    PL/SQL code is compiled by submitting it to SQL*Plus.Remember that it is advisable to type your program in anexternal editor, as you have done with SQL (see

    Introduction to Oracle).

    Debugging.

    Unless your program is an anonymous block, your errorswill notbe reported. Instead, SQL*Plus will display themessage ``warning: procedure created with compilationerrors''. You will then need to type:

    SQL> SHOW ERRORS

    to see your errors listed. If yo do not understand theerror message and you are using Oracle on UNIX, youmay be able to get a more detailed description using theoerr utility, otherwise use Oracle's documentation (see

    References section). For example, if Oracle reports``error PLS-00103'', you should type:

    oerr PLS 00103

    at the UNIX command prompt(i.e. not in SQL*Plus).

    Executing PL/SQL

    If you have submitted the program above to Oracle, youhave probably noticed that it is executed straight away.This is the case for anonymous blocks, but not forprocedures and functions. The simplest way to run a

    http://w2.syronex.com/jmr/edu/db/introduction-to-oracle/http://w2.syronex.com/jmr/edu/db/introduction-to-oracle/
  • 8/7/2019 Transaction and SQL

    27/35

    function (e.g. sysdate) is to call it from within an SQLstatement:

    SQL> SELECT sysdate FROM DUAL

    2 /

    Next, we will rewrite the anonymous block above as aprocedure. Note that we now use the user function togreet the user.

    CREATE OR REPLACE PROCEDURE welcome

    IS

    user_name VARCHAR2(8) := user;

    BEGIN -- `BEGIN' ex

    dbms_output.put_line('Welcome to PL/SQL, '

    || user_name || '!');

    END;

    /

    Make sure you understand the changes made in the code: A variable user_name of type VARCHAR2 isdeclared user_name is initialisedusing the user2 built-infunction

    http://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#foot65http://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#foot65
  • 8/7/2019 Transaction and SQL

    28/35

    ``:='' is the assignmentoperator (see. Table 2)

    Once you have compiled the procedure, execute it using

    the EXEC command.

    SQL> EXEC welcome

    Both procedures and functionsshould remind you of Javamethods. The similarities and differences between themare outlined in Table 1.

    Table 1: Functions, procedures and Java methodscompared.

    Function ProcedureJava

    Method

    Parametersinput,output

    input,output

    input

    Returns value yes no optional

    Can be called

    within SQLyes no

    http://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#tbl:opshttp://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#tbl:difhttp://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#tbl:opshttp://w2.syronex.com/jmr/edu/db/introduction-to-plsql/plsql-cursors-functions#tbl:dif
  • 8/7/2019 Transaction and SQL

    29/35

  • 8/7/2019 Transaction and SQL

    30/35

    A collection of 17 FAQs to introduce PL/SQL languagefor DBA and developers. This FAQ can also be used as

    learning tutorials on creating procedures, executing

    procedures, using local variables, controlling executionflows, passing parameters and defining nestedprocedures. Topics included in this FAQ are:

    1. What Is PL/SQL?

    2. What Are the Types PL/SQL Code Blocks?

    3. How To Define an Anonymous Block?

    4. How Many Anonymous Blocks Can Be Defined?5. How To Run the Anonymous Block Again?

    6. What Is Stored Program Unit?

    7. How To Create a Stored Program Unit?

    8. How To Execute a Stored Program Unit?

    9. How Many Data Types Are Supported?

    10. What Are the Execution Control Statements?11. How To Use SQL Statements in PL/SQL?

    12. How To Process Query Result in PL/SQL?

    13. How To Create an Array in PL/SQL?

    14. How To Manage Transaction Isolation Level?

    15. How To Pass Parameters to Procedures?

    16. How To Define a Procedure inside AnotherProcedure?

    17. What Do You Think about PL/SQL?

  • 8/7/2019 Transaction and SQL

    31/35

    Sample scripts used in this FAQ assumes that you areconnected to the server with the HR user account on

    the default database instance XE. See other FAQ

    collections on how to connect to the server.

    What Is PL/SQL?

    PL/SQL is a modern, block-structured programminglanguage. It provides several features that makedeveloping powerful database applications very

    convenient. For example, PL/SQL provides proceduralconstructs, such as loops and conditional statements,that are not available in standard SQL.

    PL/SQL code runs on the server, so using PL/SQL letsyou centralize significant parts of your database

    applications for increased maintainability and security.It also enables you to achieve a significant reduction

    of network overhead in client/server applications.

    What Are the Types PL/SQL Code Blocks?

    There are 3 types of PL/SQL code blocks:

    Anonymous Block - A block of codes with no name. Itmay contain a declaration part, an execution part,

    and exception handlers. Stored Program Unit - A block of codes with a name.

    It is similar to an anonymous block. But it can takeparameters and return values.

  • 8/7/2019 Transaction and SQL

    32/35

    Trigger - A block of code that can be defined to firebased an specific event.

    How To Define an Anonymous Block?

    An anonymous block must have an execution part, whichis a group of other PL/SQL statements enclosed in theBEGIN ... END statement. Here is a script on how to

    define a simple anonymous block with SQL*Plus:

    SQL> set serveroutput on;

    SQL> begin

    2 dbms_output.put_line('Hello world!');

    3 end;

    4 /

    Hello world!

    PL/SQL procedure successfully completed.

    "set serveroutput on;" allows dbms_output.put_line()to work.

    "/" runs the anonymous block, which print the "Helloworld!" message.

    How Many Anonymous Blocks Can Be Defined?

    An anonymous block is stored in the user's currentsession without any name. So you can only define oneanonymous block at any time. If you define another

  • 8/7/2019 Transaction and SQL

    33/35

    anonymous block, the new block will replace thepreviously defined block, as shown in the following

    script:

    SQL> set serveroutput on;

    SQL> begin

    2 dbms_output.put_line('Hello world!');

    3 end;

    4 /

    Hello world!

    PL/SQL procedure successfully completed.

    SQL> begin

    2 dbms_output.put_line('This is a PL/SQL FAQ.');

    3 end;4 /

    This is a PL/SQL FAQ.

    PL/SQL procedure successfully completed.

  • 8/7/2019 Transaction and SQL

    34/35

    Advantages of PL/SQL

    These are the advantages of PL/SQL.

    Block Structures: PL SQL consists of blocks ofcode, which can be nested within each other. Eachblock forms a unit of a task or a logical module.PL/SQL Blocks can be stored in the database andreused.

    Procedural Language Capability: PL SQL consistsof procedural language constructs such asconditional statements (if else statements) andloops like (FOR loops).

    Better Performance: PL SQL engine processesmultiple SQL statements simultaneously as a singleblock, thereby reducing network traffic.

    Error Handling: PL/SQL handles errors orexceptions effectively during the execution of aPL/SQL program. Once an exception is caught,specific actions can be taken depending upon thetype of the exception or it can be displayed to theuser with a message.

    Advantages of PL/SQL:-

    1. PL/SQL is structured as it consists of blocks ofcode and hence streamlined. This makes PL/SQLhighly productive.

  • 8/7/2019 Transaction and SQL

    35/35

    2. It is highly portable, has immense error handlingmechanisms.

    3. High performance as lines of code can be sent to

    oracle. This reduces traffic.4. With the user of stored procedures, PL/SQL is

    highly secured.5. Extremely flexible and easy to learn with syntaxes

    like SELECT, INSERT, UPDATE etc.

    Advantages of PL/SQL.

    Support SQL data manipulation.Provide facilities like conditional checking, branching andlooping.Provide fast code execution since it sends SQLstatement as a block to the oracle engine.