oracle pl/sql. pl/sql originally modeled after ada originally modeled after ada created for dept. of...

44
Oracle PL/SQL Oracle PL/SQL

Upload: marlene-hancock

Post on 13-Jan-2016

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

Oracle PL/SQLOracle PL/SQL

Page 2: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 3: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 4: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 5: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

PL/SQL Block Structure PL/SQL Block Structure

Page 6: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 7: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 8: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 9: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 10: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 11: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 12: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

Structure of Exception SectionStructure of Exception Section

Page 13: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 14: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

IF-THEN StructureIF-THEN Structure

Page 15: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

IF-THEN-ELSE StructureIF-THEN-ELSE Structure

Page 16: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

IF-THEN-ELSIF StructureIF-THEN-ELSIF Structure

Page 17: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

Stored ProceduresStored Procedures

Page 18: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 19: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 20: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

Stored FunctionsStored Functions

Like a procedure except they return Like a procedure except they return a single valuea single value

Page 21: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 22: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 23: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

TriggersTriggers

Page 24: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 25: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

TriggersTriggers

Page 26: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 27: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

Trigger EventsTrigger Events

Three types of events are availableThree types of events are available• DML eventsDML events• DDL eventsDDL events• Database eventsDatabase events

Page 28: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

DML EventsDML Events

Changes to data in a tableChanges to data in a table• InsertInsert• UpdateUpdate• DeleteDelete

Page 29: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 30: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

Database EventsDatabase Events

Server ErrorsServer Errors Users Log On or OffUsers Log On or Off Database Started or StoppedDatabase Started or Stopped

Page 31: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 32: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 33: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 34: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

Event ExamplesEvent Examples

Page 35: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 36: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 37: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 38: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 39: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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;

Page 40: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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;

Page 41: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 42: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 43: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded

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

Page 44: Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded