48
Overview Overview - - Stored Procedures Stored Procedures and Triggers and Triggers

Overview - Stored Procedures and Triggers. McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved. Outline Database programming

  • View
    213

  • Download
    0

Embed Size (px)

Citation preview

OverviewOverview - - Stored Procedures and Stored Procedures and TriggersTriggers

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Outline Outline

Database programming language background

Stored proceduresTriggers

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Motivation for Database Motivation for Database Programming LanguagesProgramming LanguagesDefinition: a procedural language with an

interface to one or more DBMSs. The interface allows a program to combine procedural statements with nonprocedural database access.

Efficiency and portability

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Design IssuesDesign Issues

Language style: call-level vs. statement-level interface

Binding: static vs. dynamicDatabase connection: implicit vs. explicitResult processing: data types and

processing orientation

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Language StyleLanguage Style

Call-level interface: a set of procedures and a set of type definitions for manipulating the results of SQL statements

Statement-level interface: changes to the syntax of a host programming language to accommodate embedded SQL statements

Most DBMSs support both interfacesODBC and JDBC are widely used call-

level interfaces

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

BindingBinding

Association of access plan with an SQL statement

Static binding: association at compile time Dynamic binding: association at run time Binding options:

– Static and dynamic for statement-level interface

– Dynamic for call-level interface

– Reuse of access plans for repetitively executed statements in a program

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Database ConnectionDatabase Connection

Implicit for stored procedures and triggers because they are part of a database

External programs: explicit connection– CONNECT statement or procedure– Web address or database identifier– Database identifier is more flexible

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Results ProcessingResults Processing

Data type mapping Processing orientation

– SELECT USING for single row results– Cursor for multiple row results– Cursor is similar to a dynamic array– Interface provides statements or procedures to

declare, open, close, iterate (position), and retrieve values

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Overview of PL/SQLOverview of PL/SQL

Proprietary database programming language for Oracle

Widely used languageJava style syntax with a statement level

interfaceUse PL/SQL for writing stored procedures

and triggers

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

User Identifiers in PL/SQLUser Identifiers in PL/SQL

Provide names for variables and constants Not case sensitiveRestrictions

– At most 30 characters– Must begin with a letter– Must be unique– Allowable characters are letters, numbers, _,

#, and $

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

PL/SQL ConstantsPL/SQL Constants

Numeric constants: whole numbers, fixed decimal numbers, and scientific notation

String constants: use single quotes; case sensitive

Boolean constants: TRUE, FALSENULL: constant for every data typeNo string constants: use the To_Date

function to create string constants

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

PL/SQL Data TypesPL/SQL Data Types

String: CHAR(L), VARCHAR2(L)Numeric: INTEGER, DECIMAL(W,D),

FLOAT(P). SMALLINTLogical: BOOLEANDATE: stores both date and time

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Variable Declaration ExamplesVariable Declaration Examples

DECLARE aFixedLengthString CHAR(6) DEFAULT 'ABCDEF'; aVariableLengthString VARCHAR2(30); anIntegerVariable INTEGER := 0; aFixedPrecisionVariable DECIMAL(10,2); -- Uses the SysDate function for the default value aDateVariable DATE DEFAULT SysDate;-- Anchored declarations anOffTerm Offering.OffTerm%TYPE; anOffYear Offering.OffYear%TYPE; aCrsUnits Course.CrsUnits%TYPE; aSalary1 DECIMAL(10,2); aSalary2 aSalary1%TYPE;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Assignment ExamplesAssignment Examples

aFixedLengthString := 'XYZABC';-- || is the string concatenation functionaVariableLengthString := aFixedLengthString || 'ABCDEF';anIntegerVariable := anAge + 1;aFixedPrecisionVariable := aSalary * 0.10;-- To_Date is the date conversion functionaDateVariable := To_Date('30-Jun-2003');

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

IF Statement FormatIF Statement Format

IF-THEN Statement: IF condition THEN sequence of statements END IF;

IF-THEN-ELSE Statement: IF condition THEN sequence of statements 1ELSE sequence of statements 2END IF;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

CASE Statement FormatCASE Statement Format

CASE Statement (Oracle 9i only): CASE selector WHEN expression1 THEN sequence of statements 1 WHEN expression2 THEN sequence of statements 2 WHEN expressionN THEN sequence of statements N [ ELSE sequence of statements N+1 ]END CASE;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Formats of Iteration StatementsFormats of Iteration StatementsFOR LOOP Statement: FOR variable IN BeginExpr .. EndExpr LOOP sequence of statementsEND LOOP;

WHILE LOOP Statement: WHILE condition LOOP sequence of statementsEND LOOP;

LOOP Statement: LOOP sequence of statements containing an EXIT statementEND LOOP;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Common SQL *Plus CommandsCommon SQL *Plus Commands

CONNECT: login to a databaseDESCRIBE: list table detailsEXECUTE: execute statementsHELP: lists column detailsSET: assigns values to SQL *Plus

environment variablesSHOW: displays error detailsSPOOL: send output to a file

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

PL/SQL BlocksPL/SQL Blocks• Anonymous blocks to test procedures and triggers

• Named blocks for stored procedures

Block Structure: [ DECLARE sequence of declarations ]BEGIN sequence of statements[ EXCEPTION sequence of statements to respond to exceptions ]END;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Anonymous Block ExampleAnonymous Block ExampleSET SERVEROUTPUT ON; -- SQL Plus command-- Anonymous blockDECLARE TmpSum INTEGER; TmpProd INTEGER; Idx INTEGER;BEGIN TmpSum := 0; TmpProd := 1; -- Use a loop to compute the sum and product FOR Idx IN 1 .. 10 LOOP TmpSum := TmpSum + Idx; TmpProd := TmpProd * Idx; END LOOP;Dbms_Output.Put_Line('Sum is ' || To_Char(TmpSum)); Dbms_Output.Put_Line('Product is ' || To_Char(TmpProd));END;/

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Motivation for Stored ProceduresMotivation for Stored Procedures

Compilation of programming language statements and SQL statements

Management of dependencies by the DBMS

Centralized management of proceduresDevelopment of more complex functions

and proceduresUsage of DBMS security system for stored

procedures

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Format of PL/SQL ProceduresFormat of PL/SQL ProceduresCREATE [OR REPLACE] PROCEDURE ProcedureName [ (Parameter1, …, ParameterN) ]IS [ sequence of declarations ]BEGIN sequence of statements[ EXCEPTION sequence of statements to respond to exceptions ]END;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Simple Procedure ExampleSimple Procedure ExampleCREATE OR REPLACE PROCEDURE pr_InsertRegistration(aRegNo IN Registration.RegNo%TYPE, aStdSSN IN Registration.StdSSN%TYPE, aRegStatus IN Registration.RegStatus%TYPE, aRegDate IN Registration.RegDate%TYPE, aRegTerm IN Registration.RegTerm%TYPE, aRegYear IN Registration.RegYear%TYPE) IS-- Create a new registrationBEGIN

INSERT INTO Registration (RegNo, StdSSN, RegStatus, RegDate, RegTerm, RegYear)VALUES (aRegNo, aStdSSN, aRegStatus, aRegDate, aRegTerm, aRegYear);dbms_output.put_line('Added a row to the table');END;/

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Exception ExampleException ExampleCREATE OR REPLACE PROCEDURE pr_InsertRegistration(aRegNo IN Registration.RegNo%TYPE, aStdSSN IN Registration.StdSSN%TYPE, aRegStatus IN Registration.RegStatus%TYPE, aRegDate IN Registration.RegDate%TYPE, aRegTerm IN Registration.RegTerm%TYPE, aRegYear IN Registration.RegYear%TYPE, aResult OUT BOOLEAN ) IS-- aResult is TRUE if successful, false otherwise.BEGINaResult := TRUE;INSERT INTO Registration (RegNo, StdSSN, RegStatus, RegDate, RegTerm, RegYear)VALUES (aRegNo, aStdSSN, aRegStatus, aRegDate, aRegTerm, aRegYear);EXCEPTION WHEN OTHERS THEN aResult := FALSE;END;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Common Predefined ExceptionsCommon Predefined Exceptions

Cursor_Already_Open Dup_Val_On_IndexInvalid_CursorNo_Data_FoundRowtype_MismatchTimeout_On_ResourceToo_Many_Rows

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Format of PL/SQL FunctionsFormat of PL/SQL FunctionsCREATE [OR REPLACE] FUNCTION FunctionName [ (Parameter1, …, ParameterN) ]RETURN DataTypeIS [ sequence of declarations ]BEGIN sequence of statements including a RETURN statement[ EXCEPTION sequence of statements to respond to exceptions ]END;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Simple Function ExampleSimple Function ExampleCREATE OR REPLACE FUNCTION fn_RetrieveStdName(aStdSSN IN Student.StdSSN%type) RETURN VARCHAR2 ISaFirstName Student.StdFirstName%type;aLastName Student.StdLastName%type;

BEGINSELECT StdFirstName, StdLastName INTO aFirstName, aLastName FROM Student WHERE StdSSN = aStdSSN;RETURN(aLastName || ', ' || aFirstName);EXCEPTIONWHEN No_Data_Found THEN RETURN(NULL); WHEN OTHERS THEN raise_application_error(-20001, 'Database error');END;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

PL/SQL CursorsPL/SQL Cursors

Supports usage of SQL statements that return a collection of rows

Declaration statementsSpecialized FOR statementCursor attributesActions on cursors

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Classification of CursorsClassification of Cursors

Statement binding: – Static: SQL statement specified at compile-time– Dynamic: SQL statement specified at execution

Declaration status– Implicit: declared, opened, and iterated inside a

FOR statement– Explicit: declared with the CURSOR statement

in the DECLARE section

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Common Cursor AttributesCommon Cursor Attributes

%ISOpen: true if cursor is open %Found: true if cursor is not empty

following a FETCH statement %NotFound: true if cursor is empty

following a FETCH statement %RowCount: number of rows fetched

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

PL/SQL PackagesPL/SQL Packages

Larger unit of modularityImproved reusabilityGroups procedures, functions, exceptions,

variables, constants, types, and cursors. Public interface Private body: implementation of packageOracle provides predefined packages

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Format of Package InterfaceFormat of Package Interface

CREATE [OR REPLACE] PACKAGE PackageName IS[ Constant, variable, and type declarations ][ Cursor declarations ][ Exception declarations ][ Procedure definitions ][ Function definitions ]END PackageName;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Format of Package BodyFormat of Package Body

CREATE [OR REPLACE] PACKAGE BODY PackageName IS[ Variable and type declarations ][ Cursor declarations ][ Exception declarations ][ Procedure implementations ][ Function implementations ][ BEGIN sequence of statements ][ EXCEPTION exception handling statements ]END PackageName;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Trigger OverviewTrigger Overview

Event-Condition-Action (ECA) rulesManaged by DBMSExecution controlled by inference engineDBMS extended with inference enginePart of SQL:1999 Widely implemented before SQL:1999

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Typical Usage of TriggersTypical Usage of Triggers

Complex integrity constraintsTransition constraintsUpdate propagationException reportingAudit trail

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Classification of TriggersClassification of Triggers

Granularity– Row: fire for each modified row– Statement: fire once per statement

Timing: before or afterEvent

– Manipulation statements– Update event with a list of columns

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Format of Oracle TriggersFormat of Oracle Triggers

CREATE [OR REPLACE] TRIGGER TriggerNameTriggerTiming TriggerEvent[ Referencing clause ][ FOR EACH ROW ][ WHEN ( Condition ) ][ DECLARE sequence of declarative statements ]BEGIN sequence of statements [ EXCEPTION exception handling statements ]END;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

AFTER ROW Trigger ExampleAFTER ROW Trigger Example

CREATE OR REPLACE TRIGGER tr_Enrollment_IA-- This trigger updates the number of enrolled-- students the related offering row.AFTER INSERTON EnrollmentFOR EACH ROWBEGIN UPDATE Offering SET OffNumEnrolled = OffNumEnrolled + 1 WHERE OfferNo = :NEW.OfferNo;EXCEPTION WHEN OTHERS THEN RAISE_Application_Error(-20001, 'Database error');END;

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Guide to Trigger ExamplesGuide to Trigger Examples

BEFORE ROW: – Complex integrity constraints– Transition constraints– Standardization of data

AFTER ROW– Update propagation– Audit trail– Exception reporting

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Compound Events in TriggersCompound Events in Triggers

Compound events – Use OR to specify multiple events

– Trigger body can detect the event Multiple triggers versus compound event triggers

– More triggers but less complex

– Fewer, more complex triggers

– Trigger interaction increases with the number of triggers

– No clear preference

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Trigger Execution ProcedureTrigger Execution Procedure

Inference engine that controls trigger firing Specifies execution order among triggers,

integrity constraints, and manipulation statements

Trigger body execution can cause other triggers to fire

SQL: standard trigger execution procedureMost DBMSs deviate from the standard

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Simplified Oracle Trigger Simplified Oracle Trigger Execution ProcedureExecution Procedure

1. Execute the applicable BEFORE STATEMENT triggers.2. For each row affected by the SQL manipulation statement:

2.1 Execute the applicable BEFORE ROW triggers.2.2 Perform the data manipulation operation on the row.2.3 Perform integrity constraint checking.2.4 Execute the applicable AFTER ROW triggers.

3. Perform deferred integrity constraint checking.4. Execute the applicable AFTER statement triggers.

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Overlapping TriggersOverlapping Triggers

Definition:– Two or more triggers with the same timing,

granularity, and applicable event– Same SQL statement causes both triggers to

fireSQL:1999: firing order based on trigger

creation timeOracle: arbitrary firing orderCarefully analyze overlapping triggers

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Recursive Trigger ExecutionRecursive Trigger Execution

1. Execute the applicable BEFORE STATEMENT triggers.2. For each row affected by the SQL manipulation statement

2.1. Execute the applicable BEFORE ROW triggers. Recursively execute the procedure for data manipulation statements in a trigger.

2.2. Perform the data manipulation operation on the row.2.3. Perform integrity constraint checking. Recursively

execute the procedure for actions on referenced rows.2.4. Execute the applicable AFTER ROW triggers.

Recursively execute the procedure for data manipulation statements in a trigger.

3. Perform deferred integrity constraint checking.4. Execute the applicable AFTER statement triggers.

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Controlling Trigger ComplexityControlling Trigger Complexity Do not use data manipulation statements in

BEFORE triggers. Limit data manipulation statements in AFTER

triggers. For triggers that fire on UPDATE statements,

always list the columns in which the trigger applies.

Ensure that overlapping triggers do not depend on a specific order to fire.

Be cautious about triggers on tables affected by actions on referenced rows.

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Mutating Table ErrorsMutating Table Errors

Restriction on trigger execution in Oracle Mutating tables of a trigger:

– Table in which trigger is defined– Related tables affected by CASCADE

DELETEOracle prohibits SQL statements in a

trigger body on mutating tablesRun-time error during trigger execution

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

Resolving Mutating Table ErrorsResolving Mutating Table Errors

Avoid by using new and old values Sometimes unavoidable

– Trigger to enforce integrity among rows of the same table

– Trigger to insert a related row in a child table with DELETE CASCADE

Resolutions– Package and a collection of triggers– Use INSTEAD OF trigger for a view

McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved.

SummarySummary

Stored procedures and triggers are important for database application development and database administration

Benefits for DBMS management of stored procedures

Classification of triggers by granularity, timing, event, and purpose

Knowledge of trigger execution procedures