Oracle PL/SQL Oracle PL/SQL
Feb 05, 2016
Oracle PL/SQLOracle PL/SQL
PL/SQLPL/SQL
Originally modeled after ADAOriginally modeled after ADA• Created for Dept. of DefenseCreated for Dept. of Defense
Allows expanded functionality of Allows expanded functionality of database applicationsdatabase applications
Continues to improve with each new Continues to improve with each new database releasedatabase release
PL/SQLPL/SQL FeaturesFeatures
• Tight integration with SQLTight integration with SQL Supports data types, functions, pseudo-columns, etc.Supports data types, functions, pseudo-columns, etc.
• Increased performanceIncreased performance A block of statements sent as a single statementA block of statements sent as a single statement
• Increased productivityIncreased productivity Same techniques can be used with most Oracle Same techniques can be used with most Oracle
productsproducts• PortabilityPortability
Works on any Oracle platformWorks on any Oracle platform• Tighter securityTighter security
Users may access database objects without granted Users may access database objects without granted privilegesprivileges
PL/SQL ProgramsPL/SQL Programs
Declaration section (optional)Declaration section (optional)• Any needed variables declared hereAny needed variables declared here
Executable or begin sectionExecutable or begin section• Program code such as statements to Program code such as statements to
retrieve or manipulate data in a tableretrieve or manipulate data in a table Exception section (optional)Exception section (optional)
• Error traps can catch situations which Error traps can catch situations which might ordinarily crash the programmight ordinarily crash the program
PL/SQL Block Structure PL/SQL Block Structure
PL/SQL VariablesPL/SQL Variables Variables are local to the code blockVariables are local to the code block Names can be up to 30 characters long and Names can be up to 30 characters long and
must begin with a charactermust begin with a character Declaration is like that in a tableDeclaration is like that in a table
• Name then data type the semi-colonName then data type the semi-colon• Can be initialized using := operator in the Can be initialized using := operator in the
declarationdeclaration• Can be changed with := in the begin sectionCan be changed with := in the begin section• Can use constraintsCan use constraints
Variables can be composite or collection Variables can be composite or collection typestypes• Multiple values of different or same typeMultiple values of different or same type
Common PL/SQL Data TypesCommon PL/SQL Data Types
• CHAR ( max_length )CHAR ( max_length )• VARCHAR2 ( max_length )VARCHAR2 ( max_length )• NUMBER ( precision, scale )NUMBER ( precision, scale )• BINARY_INTEGER – more efficient than numberBINARY_INTEGER – more efficient than number• RAW ( max_length )RAW ( max_length )• DATEDATE• BOOLEAN (true, false, null)BOOLEAN (true, false, null)• Also LONG, LONG RAW and LOB types but the Also LONG, LONG RAW and LOB types but the
capacity is usually less in PL/SQL than SQLcapacity is usually less in PL/SQL than SQL
PL/SQL Variable ConstraintsPL/SQL Variable Constraints
NOT NULLNOT NULL• Can not be emptyCan not be empty
CONSTANTCONSTANT• Can not be changedCan not be changed
PL/SQL Variables ExamplesPL/SQL Variables Examples
Age number;Age number;
Last char ( 10 );Last char ( 10 );
DVal Date := Sysdate;DVal Date := Sysdate;
SID number not null;SID number not null;
Adjust constant number := 1;Adjust constant number := 1;
CanLoop boolean := trueCanLoop boolean := true
Predefined ExceptionsPredefined Exceptions
INVALID_NUMBER (ORA-01722)INVALID_NUMBER (ORA-01722)• Attempted to store non-numeric data in a Attempted to store non-numeric data in a
variable with a numeric data typevariable with a numeric data type NO_DATA_FOUND (ORA-01403)NO_DATA_FOUND (ORA-01403)
• Query resulted in no rows being foundQuery resulted in no rows being found NOT_LOGGED_ON (ORA-01012)NOT_LOGGED_ON (ORA-01012)
• Not currently connected to an Oracle Not currently connected to an Oracle databasedatabase
TOO_MANY_ROWS (ORA-01422)TOO_MANY_ROWS (ORA-01422)• A SELECT INTO statement returned more A SELECT INTO statement returned more
than one rowthan one row
Predefined Exceptions (cont.)Predefined Exceptions (cont.)
DUP_VALUE_ON_INDEX (ORA-00001DUP_VALUE_ON_INDEX (ORA-00001))• Value inserted for a primary key is not Value inserted for a primary key is not
uniqueunique VALUE_ERRORVALUE_ERROR ( (ORA-06502ORA-06502))
• The value being placed in a variable is the The value being placed in a variable is the wrong length or data typewrong length or data type
ZERO_DIVIDE (ORA-01476)ZERO_DIVIDE (ORA-01476)• An attempt was made to divide a number An attempt was made to divide a number
by zeroby zero
Structure of Exception SectionStructure of Exception Section
Conditional StructuresConditional Structures
IF-THENIF-THEN
IF-THEN-ELSEIF-THEN-ELSE
IF-THEN-ELSIFIF-THEN-ELSIF• An alternative to nested IF-THEN_ELSEAn alternative to nested IF-THEN_ELSE
IF-THEN StructureIF-THEN Structure
IF-THEN-ELSE StructureIF-THEN-ELSE Structure
IF-THEN-ELSIF StructureIF-THEN-ELSIF Structure
Stored ProceduresStored Procedures
Stored ProceduresStored Procedures
The first line is called the The first line is called the Procedure Procedure SpecificationSpecification
The remainder is the The remainder is the Procedure BodyProcedure Body A procedure is compiled and loaded A procedure is compiled and loaded
in the database as an objectin the database as an object Procedures can have parameters Procedures can have parameters
passed to thempassed to them
Stored ProceduresStored Procedures
Run a procedure with the PL/SQL Run a procedure with the PL/SQL EXECUTE commandEXECUTE command
Parameters are enclosed in Parameters are enclosed in parenthesesparentheses
Stored FunctionsStored Functions
Like a procedure except they return Like a procedure except they return a single valuea single value
TriggersTriggers
Associated with a particular tableAssociated with a particular table Automatically executed when a Automatically executed when a
particular event occursparticular event occurs• InsertInsert• UpdateUpdate• DeleteDelete• OthersOthers
Triggers vs. ProceduresTriggers vs. Procedures
Procedures are Procedures are explicitlyexplicitly executed by executed by a user or applicationa user or application
Triggers are Triggers are implicitlyimplicitly executed executed (fired) when the triggering event (fired) when the triggering event occursoccurs
Triggers should not be used as a lazy Triggers should not be used as a lazy way to invoke a procedure as they way to invoke a procedure as they are fired are fired everyevery time the event occurs time the event occurs
TriggersTriggers
TriggersTriggers
The The trigger specificationtrigger specification names the names the trigger and indicates when it will firetrigger and indicates when it will fire
The The trigger bodytrigger body contains the PL/SQL contains the PL/SQL code to accomplish whatever task(s) code to accomplish whatever task(s) need to be performedneed to be performed
TriggersTriggers
Triggers TimingTriggers Timing
A triggers timing has to be specified A triggers timing has to be specified firstfirst• Before (most common)Before (most common)
Trigger should be fired before the operationTrigger should be fired before the operation• i.e. before an inserti.e. before an insert
• AfterAfter Trigger should be fired after the operationTrigger should be fired after the operation
• i.e. after a delete is performed i.e. after a delete is performed
Trigger EventsTrigger Events
Three types of events are availableThree types of events are available• DML eventsDML events• DDL eventsDDL events• Database eventsDatabase events
DML EventsDML Events
Changes to data in a tableChanges to data in a table• InsertInsert• UpdateUpdate• DeleteDelete
DDL EventsDDL Events
Changes to the definition of objectsChanges to the definition of objects• TablesTables• IndexesIndexes• ProceduresProcedures• FunctionsFunctions• OthersOthers
Include CREATE, ALTER and DROP Include CREATE, ALTER and DROP statements on these objectsstatements on these objects
Database EventsDatabase Events
Server ErrorsServer Errors Users Log On or OffUsers Log On or Off Database Started or StoppedDatabase Started or Stopped
Trigger DML EventsTrigger DML Events
Can specify one or more events in Can specify one or more events in the specificationthe specification• i.e. INSERT OR UPDATE OR DELETEi.e. INSERT OR UPDATE OR DELETE
Can specify one or more columns to Can specify one or more columns to be associated with a type of eventbe associated with a type of event• i.e. BEFORE UPDATE OF SID OR SNAMEi.e. BEFORE UPDATE OF SID OR SNAME
Table NameTable Name
The next item in the trigger is the The next item in the trigger is the name of the table to be affectedname of the table to be affected
Trigger LevelTrigger Level
Two levels for TriggersTwo levels for Triggers• Row-level triggerRow-level trigger
Requires FOR EACH ROW clauseRequires FOR EACH ROW clause• If operation affects multiple rows, trigger fires If operation affects multiple rows, trigger fires
once for each row affectedonce for each row affected
• Statement-level triggerStatement-level trigger• DML triggers should be row-levelDML triggers should be row-level• DDL and Database triggers should not DDL and Database triggers should not
be row-levelbe row-level
Event ExamplesEvent Examples
TriggersTriggers
Conditions Available So Multiple Conditions Available So Multiple Operations Can Be Dealt With In Operations Can Be Dealt With In Same TriggerSame Trigger• Inserting, Updating, DeletingInserting, Updating, Deleting
Column Prefixes Allow Identification Column Prefixes Allow Identification Of Value ChangesOf Value Changes• New, OldNew, Old
Triggers ExceptionsTriggers Exceptions
EXCEPTION Data Type Allows Custom EXCEPTION Data Type Allows Custom ExceptionsExceptions
RAISE Allows An Exception To Be RAISE Allows An Exception To Be Manually OccurManually Occur
RAISE_APPLICATION_ERROR Allows RAISE_APPLICATION_ERROR Allows Termination Using A Custom Error Termination Using A Custom Error MessageMessage• Must Be Between -20000 and -20999Must Be Between -20000 and -20999• Message Can Be Up to 512 BytesMessage Can Be Up to 512 Bytes
CursorsCursors
Cursors Hold Result of an SQL Cursors Hold Result of an SQL StatementStatement
Two Types of Cursors in PL/SQLTwo Types of Cursors in PL/SQL• Implicit – Automatically Created When a Implicit – Automatically Created When a
Query or Manipulation is for a Single Query or Manipulation is for a Single RowRow
• Explicit – Must Be Declared by the UserExplicit – Must Be Declared by the User Creates a Unit of Storage Called a Result SetCreates a Unit of Storage Called a Result Set
CursorsCursors
Result SetResult Set
MIS380 MIS380 DATABASE DESIGNDATABASE DESIGN 44MIS202 MIS202 INFORMATION SYSTEMS INFORMATION SYSTEMS 3 3
<Cursor<Cursor
MIS485 MIS485 MANAGING TECHNOLOGYMANAGING TECHNOLOGY 44
MIS480 MIS480 ADVANCED DATABASE ADVANCED DATABASE 44
CursorsCursors
Declaring an Explicit CursorDeclaring an Explicit Cursor
CURSOR CursorName IS SelectStatement;CURSOR CursorName IS SelectStatement; Opening an Explicit CursorOpening an Explicit Cursor
OPEN CursorName;OPEN CursorName; Accessing Rows from an Explicit Accessing Rows from an Explicit
CursorCursor
FETCH CursorName INTO RowVariables;FETCH CursorName INTO RowVariables;
CursorsCursors
Declaring Variables of the Proper Declaring Variables of the Proper Type with %TYPEType with %TYPEVarName TableName.FieldName%TYPE;VarName TableName.FieldName%TYPE;
Declaring Variables to Hold An Entire Declaring Variables to Hold An Entire RowRowVarName CursorName%ROWTYPE;VarName CursorName%ROWTYPE;
Releasing the Storage Area Used by Releasing the Storage Area Used by an Explicit Cursoran Explicit CursorCLOSE CursorName;CLOSE CursorName;
Iterative StructuresIterative Structures
LOOP … EXIT … END LOOPLOOP … EXIT … END LOOP• EXIT with an If Avoids Infinite LoopEXIT with an If Avoids Infinite Loop
LOOP … EXIT WHEN … END LOOPLOOP … EXIT WHEN … END LOOP• Do Not Need An If to Control EXITDo Not Need An If to Control EXIT
WHILE … LOOP … END LOOPWHILE … LOOP … END LOOP• Eliminates Need for EXITEliminates Need for EXIT
FOR … IN … END LOOPFOR … IN … END LOOP• Eliminates Need for Initialization of Eliminates Need for Initialization of
CounterCounter
Cursor Control With LoopsCursor Control With Loops
Need a Way to Fetch RepetitivelyNeed a Way to Fetch Repetitively Need a Way to Determine How Many Need a Way to Determine How Many
Rows to Process With a CursorRows to Process With a Cursor• Cursor AttributesCursor Attributes
CursorName%ROWCOUNT – Number of CursorName%ROWCOUNT – Number of Rows in a Result SetRows in a Result Set
CursorName%FOUND – True if a Fetch CursorName%FOUND – True if a Fetch Returns a RowReturns a Row
CursorName%NOTFOUND – True if CursorName%NOTFOUND – True if Fetch Goes Past Last RowFetch Goes Past Last Row
Cursor For LoopCursor For Loop
Processing an Entire Result Set Processing an Entire Result Set CommonCommon
Special Form of FOR … IN to Manage Special Form of FOR … IN to Manage CursorsCursors
No Need for Separate OPEN, FETCH No Need for Separate OPEN, FETCH and CLOSE statementsand CLOSE statements
Requires %ROWTYPE VariableRequires %ROWTYPE Variable