ExtensionExtension toto SQL:SQL: View,View, Triggers,Triggers, CursorCursor

SSSS ChungChung

1 ViewsViews (Virtual(Virtual Tables)Tables) inin SQLSQL

 ConceptConcept ofof aa viewview inin SQLSQL  SingleSingle tabletable derivedderived fromfrom otherother tablestables  ConsideredConsidered toto bebe aa virtualvirtual tabletable

2 SpecificationSpecification ofof ViewsViews inin SQLSQL

 CREATECREATE VIEWVIEW commandcommand  GiveGive TableTable (View)(View) name,name, listlist ofof attributeattribute namesnames forfor thethe ViewView (),(table), andand aa QueryQuery toto specifyspecify thethe contentscontents ofof thethe ViewView

3 AlteringAltering ExistingExisting ViewView

ReplaceReplace ViewView Existing_View_NameExisting_View_Name AsAs SelectSelect …… FromFrom …… WhereWhere ……;;

ReplaceReplace ViewView Works_On1Works_On1 AsAs SelectSelect FnameFname ,, LnameLname ,, PnoPno ,, PnamePname ,, HoursHours FromFrom Employee,Employee, Works_OnWorks_On ,, ProjectProject WhereWhere SsnSsn == EssnEssn andand PnoPno == PnumberPnumber

4 SpecificationSpecification ofof ViewsViews inin SQLSQL (cont(cont ’’d.)d.)  SpecifySpecify SQLSQL queriesqueries onon aa viewview  ViewView alwaysalways upup --toto --datedate  ResponsibilityResponsibility ofof thethe DBMSDBMS andand notnot thethe useruser  DROPDROP VIEWVIEW commandcommand  DisposeDispose ofof aa viewview

5 ViewsViews

Students ( sid , name, address, gpa ) Completed ( sid , course , grade) A is a query stored in the – Think of it as a table definition for future use Example view definition: CREATE VIEW GS tudents AS SELECT * FROM Students WHERE gpa >= 2.5 Views can be used like base tables , in any query or in any other view. Like a Macro. Different from Insert INTO.

6 ExampleExample viewview use:use: simplersimpler queriesqueries

SupposeSuppose youyou wantwant toto retrieveretrieve goodgood studentsstudents whowho havehave completedcompleted CIS430.CIS430. GSGS tudentstudents ((sidsid ,, name,name, address,address, gpagpa )) SELECTSELECT S.name,S.name, S.phoneS.phone FROMFROM GstudentsGstudents SS INNERINNER JOINJOIN CompletedCompleted CC ONON S.sidS.sid == C.sidC.sid WHEREWHERE C.courseC.course == ‘‘CIS430CIS430 ’’;;

ItIt ’’ss easiereasier toto writewrite thethe queryquery usingusing thethe view.view. 7 ViewsViews forfor SecuritySecurity

ThisThis isis thethe studentstudent tabletable withoutwithout thethe gpagpa fieldfield toto hidehide gpagpa toto anyany useruser inin DB.DB.

CREATECREATE VIEWVIEW SstudentsSstudents ASAS SELECTSELECT sidsid ,, name,name, addressaddress FROMFROM studentsstudents

8 ViewsViews forfor ExtensibilityExtensibility

An old company ’s database includes a table: Part ( PartID , Name, Weight) Weight is stored in pounds The company is purchased by a new firm that uses metric weights The two , old and new , must be integrated and use Kg. But there ’s lots of old software using pounds. Solution: views!

9 ViewsViews forfor extensibilityextensibility (( ctdctd ))

Solution:Solution: 1.1. BaseBase tabletable withwith kilograms:kilograms: NewPartNewPart forfor newnew integratedintegrated companycompany 2.2. CREATECREATE VIEWVIEW PartPart ASAS SELECTSELECT PartIDPartID ,, Name,Name, 2.2046*2.2046* WeightWeight FROMFROM NewPartNewPart ;; 3.3. OldOld programsprograms stillstill callcall thethe tabletable ““PartPart ””

10 ViewView UpdateUpdate andand InlineInline ViewsViews

ClauseClause WITHWITH CHECKCHECK OPTIONOPTION  MustMust bebe addedadded atat thethe endend ofof thethe viewview definitiondefinition ifif aa viewview isis toto bebe updatedupdated InIn --lineline viewview (dynamic(dynamic Table)Table)  DefinedDefined inin thethe FROMFROM clauseclause ofof anan SQLSQL queryquery

11 ViewView Implementation,Implementation, ViewView Update,Update, andand InlineInline ViewsViews  ComplexComplex problemproblem ofof efficientlyefficiently implementingimplementing aa viewview forfor queryingquerying  QueryQuery modificationmodification approachapproach  ModifyModify viewview queryquery intointo aa queryquery onon underlyingunderlying basebase tablestables  Disadvantage:Disadvantage: inefficientinefficient forfor viewsviews defineddefined viavia complexcomplex queriesqueries thatthat areare timetime --consumingconsuming toto executeexecute

12 ViewView ImplementationImplementation

 ViewView materializationmaterialization approachapproach  PhysicallyPhysically createcreate aa temporarytemporary viewview tabletable whenwhen thethe viewview isis firstfirst queriedqueried  KeepKeep thatthat tabletable onon thethe assumptionassumption thatthat otherother queriesqueries onon thethe viewview willwill followfollow  RequiresRequires efficientefficient strategystrategy forfor automaticallyautomatically updatingupdating thethe viewview tabletable whenwhen thethe basebase tablestables areare updatedupdated

13 ViewView ImplementationImplementation (cont(cont ’’d.)d.)

 IncrementalIncremental updateupdate strategiesstrategies  DBMSDBMS determinesdetermines whatwhat newnew tuplestuples mustmust bebe inserted,inserted, deleted,deleted, oror modifiedmodified inin aa materializedmaterialized viewview tabletable

14 ProblemProblem withwith views:views: updateupdate

Views cannot always be updated unambiguously. Consider EmpEmp ((((empidempid ,, enameename ,, address,address, deptiddeptid )))) DeptDept (( deptiddeptid ,, dnamedname )))) CREATECREATE VIEWVIEW EMPDEPTEMPDEPT ASASASAS SELECTSELECT enameename ,, dnamedname FROMFROM EmpEmp InnerJOINInnerJOIN DeptDept ONON Emp.deptidEmp.deptid ====Dept.deptidDept.deptid ;;;; EMPDEPTEMPDEPT enameename dnamedname jimjimjimjim shoeshoe joejoejoejoe suitsuit

I want to ( jim , shoe) from EMPDEPT. Can I do that? 15 ViewView UpdateUpdate

ViewView cancan bebe updatedupdated ifif ––ItIt isis defineddefined onon aa singlesingle basebase tabletable ––UsingUsing onlyonly SelectionSelection andand ProjectionProjection ––NoNo AggregatesAggregates ––NoNo DISTINCTDISTINCT

16 ViewView UpdateUpdate andand InlineInline ViewsViews

 UpdateUpdate onon aa viewview defineddefined onon aa singlesingle tabletable withoutwithout anyany aggregateaggregate functionsfunctions  CanCan bebe mappedmapped toto anan updateupdate onon underlyingunderlying basebase tabletable  ViewView involvinginvolving joinsjoins cancan NOTNOT bebe updatedupdated  OftenOften notnot possiblepossible forfor DBMSDBMS toto determinedetermine whichwhich ofof thethe updatesupdates isis intendedintended

17 LevelsLevels ofof AbstractionAbstraction

External view; user and data designer ES 1 ES 2 ES 3 Logical storage; data designer Conceptual Schema

Physical Schema Physical storage; DBA

18 PhysicalPhysical SchemaSchema TheThe physicalphysical schemaschema isis aa descriptiondescription ofof howhow thethe datadata isis physicallyphysically storedstored inin thethe database.database. ItIt includesincludes –– WhereWhere thethe datadata isis locatedlocated –– FileFile structuresstructures –– AccessAccess methodsmethods –– IndexesIndexes TheThe physicalphysical schemaschema isis managedmanaged byby thethe DBA.DBA.

19 ConceptualConceptual SchemaSchema

TheThe conceptualconceptual schemaschema -- aa logicallogical descriptiondescription ofof howhow thethe datadata isis stored.stored. -- ItIt consistsconsists ofof thethe schemasschemas wewe havehave describeddescribed withwith CREATECREATE TABLETABLE statements.statements. ItIt isis managedmanaged byby thethe datadata designer.designer.

20 ExternalExternal SchemasSchemas

EachEach externalexternal schemaschema isis aa combinationcombination ofof basebase tablestables andand views,views, tailoredtailored toto thethe needsneeds ofof aa singlesingle user.user. ItIt isis managedmanaged byby thethe datadata designerdesigner andand thethe user.user.

21 DataData IndependenceIndependence

AA databasedatabase modelmodel possessespossesses datadata independenceindependence ifif applicationapplication programsprograms areare immuneimmune toto changeschanges inin thethe conceptualconceptual andand physicalphysical schemas.schemas. WhyWhy isis thisthis important?important? EverythingEverything changes.changes. HowHow doesdoes thethe relationalrelational modelmodel achieveachieve logicallogical (conceptual)(conceptual) datadata independence?independence? –– ThroughThrough viewsviews –– IfIf thethe conceptualconceptual schemaschema changes,changes, aa viewview cancan bebe defineddefined toto preservepreserve existingexisting applicationsapplications 22 DataData IndependenceIndependence (( ctdctd .).)

How does the achieve physical data independence? 1. Conceptual level contains no physical info 2. SQL can program against the conceptual level – Earlier DBMSs (network, hierarchical) did not have these properties. – Their languages had physical properties embedded in them. That is the primary reason for the success of the relational model

23 Views:Views: SummarySummary

AA viewview isis aa storedstored queryquery definitiondefinition ViewsViews cancan bebe veryvery usefuluseful –– EasierEasier queryquery writing,writing, security,security, extensibilityextensibility ButBut viewsviews cannotcannot bebe unambiguouslyunambiguously updatedupdated ThreeThree levelslevels ofof abstractionabstraction inin aa relationalrelational DBMSDBMS –– YieldsYields datadata independence:independence: logicallogical andand physicalphysical

24 SpecifyingSpecifying ConstraintsConstraints asas AssertionsAssertions andand ActionsActions asas TriggersTriggers

 CREATECREATE ASSERTIONASSERTION  SpecifySpecify additionaladditional typestypes ofof constraintsconstraints outsideoutside scopescope ofof builtbuilt --inin relationalrelational modelmodel constraintsconstraints  CREATECREATE TRIGGERTRIGGER  SpecifySpecify automaticautomatic actionsactions thatthat databasedatabase systemsystem willwill performperform whenwhen certaincertain eventsevents andand conditionsconditions occuroccur

25 SpecifyingSpecifying GeneralGeneral ConstraintsConstraints asas AssertionsAssertions inin SQLSQL  CREATECREATE ASSERTIONASSERTION  SpecifySpecify aa queryquery thatthat selectsselects anyany tuplestuples thatthat violateviolate thethe desireddesired conditioncondition  UseUse onlyonly inin casescases wherewhere itit isis notnot possiblepossible toto useuse CHECKCHECK onon attributesattributes andand domainsdomains

26 Assertions:Assertions: ConstraintsConstraints overover MultipleMultiple RelationsRelations

CREATE TABLE Sailors Number of boats ( sid INTEGER, plus number of sname CHAR(10), sailors is < 100 rating INTEGER, ASSERTIONASSERTION age REAL, NotNot PRIMARY KEY (sid), CHECK associatedassociated ( (SELECT COUNT (S.sid) FROM Sailors S) withwith eithereither + (SELECT COUNT (B.bid) FROM Boats B) < 100 ) table.table. CREATE ASSERTION smallClub CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 ) Assertions:Assertions: CheckCheck overover severalseveral tablestables

Employee( id, name, address, mgr, salary )

CREATE ASSERTION Salary_Mgr Any logical CHECK (NOT EXISTS expression (SELECT * involving an SQL FROM Employee E, statement can be Employee M used to constrain WHERE E.salary > tables in the M.salary AND database. E.mgr = M.id ))

28 IntroductionIntroduction toto TriggersTriggers inin SQLSQL

 CREATECREATE TRIGGERTRIGGER statementstatement  UsedUsed toto monitormonitor thethe databasedatabase  TypicalTypical triggertrigger hashas threethree components:components:  Event(sEvent(s ))  ConditionCondition  ActionAction

29 TriggersTriggers (Active(Active database)database)

Trigger: A procedure that starts automatically if specified changes occur to the DBMS Analog to a "daemon" that monitors a database for certain events to occur Three parts: – Event : activates the trigger – Condition : tests whether the triggers should run [Optional] – Action : what happens if the trigger runs Semantics: – When event occurs, and condition is satisfied, the action is performed. TriggersTriggers (Not(Not aa constraint)constraint)

Three parts: – Event (activates the trigger) This will be an insert, delete and/or to a table – Condition (tests whether the triggers should run) A logical statement or a query – Action (what happens if the trigger runs) Can execute queries, execute data -definition commands, transaction -oriented commands, and host -language procedures When does the Action execute? – Specified with Event (BEFORE, AFTER) EventEvent --ConditionCondition --ActionAction (ECA)(ECA)

EEventvent occursoccurs inin databasesdatabases – e.g. addition of a new , deletion of a row CConditionsonditions areare checkedchecked – e.g. Is batch complete? Has student passed? AActionsctions areare executedexecuted ifif conditionsconditions areare satisfiedsatisfied – e.g. send batch to supplier, congratulate student

32 TriggersTriggers –– Event,Condition,ActionEvent,Condition,Action

Events could be : BEFORE|AFTER INSERT|UPDATE|DELETE ON e.g.: BEFORE INSERT ON Manager Condition is SQL expression or even an SQL query (query with non -empty result means TRUE) Action can be many different choices : – SQL statements – DDL and transaction -oriented statements like “ ”.

33 TriggerTrigger SyntaxSyntax

CREATE TRIGGER BEFORE|AFTER INSERT|DELETE|UPDATE [OF ] ON |< viewName > [REFERENCING [OLD AS ] [NEW AS ]] [FOR EACH ROW] ( OR [ FOR EACH STATEMENT ] by default) [WHEN ()] Begin End; 34 SyntaxSyntax forfor creatingcreating triggerstriggers inin SQLSQL

Trigger name - unique within one database schema Timing - depends on the order of controlled events (before or after or instead of) Triggering event - event which fires the trigger (E) Filtering condition - checked when the triggering event occurs (C) Target - table (or view) against which the trigger is fired; they should be both created within the same schema Trigger Parameters - parameters used to denote the record columns ; preceded by colon – :new, :old for new and old versions of the values respectively Trigger action - SQL statements, executed when the trigger fires; surrounded by Begin ... End (A) 35 SyntaxSyntax forfor CreatingCreating StatementStatement TriggersTriggers

CREATECREATE [OR[OR REPLACE]REPLACE] TRIGGERTRIGGER trigger_nametrigger_name timingtiming event1event1 [ [ OROR event2event2 OROR event3]event3] ONON table_nametable_name BEGINBEGIN SQLSQL statements;statements; END;END;

The trigger body consisting of SQL statements will be executed only once according to the prescribed timing, when the event1 (event2, event3) occurs against the monitored table in question table_name. 36 Triggers:Triggers: Example*Example* Assume one donation has been inserted to indiv , for simplicity

CREATECREATE TRIGGERTRIGGER MYTRIG1MYTRIG1 BEFOREBEFORE INSERTINSERT ONON AccountAccount FORFOR EACHEACH STATEMENTSTATEMENT ((------>> isis default)default) BEGINBEGIN IF (TO_CHAR (SYSDATE, ’dy ’ ) IN (‘Sat ’, ’Sun ’)) OR TO_CHAR (SYSDATE, ’hh24:mi ’ ) NOT BETWEEN ’08:00 ’ AND ’17:00 ’) THEN RAISE_APPLICATION_ERROR( -20500, ’Cannot create new account now !! ’) ; END IF; END;END; TriggersTriggers vsvs ConstraintsConstraints

Triggers are harder to understand – If multiple triggers apply, their order of execution is unspecified – One trigger can activate another, causing a chain of actions – A trigger can activate itself Triggers are more powerful than constraints – They can make changes to tables – They can take action before or after a data modification

38 VariationsVariations inin DBMSDBMS Example:TriggersExample:Triggers inin SQLSQL ServerServer An SQL Server trigger is a T/SQL procedure that is invoked when a specified database activity occurs Triggers can be used to: – Enforce business rules – Set complex default values – Update views – Implement actions SQL Server only supports INSTEAD OF and AFTER triggers: – A table may have one or more AFTER triggers – AFTER triggers may not be assigned to views – A view or table may have only one INSTEAD OF trigger for each triggering action Triggers can roll back the transactions that caused them to be fired 39 TypesTypes ofof SQLSQL TriggersTriggers HowHow manymany timestimes shouldshould thethe triggertrigger bodybody executeexecute whenwhen thethe triggeringtriggering eventevent takestakes place?place? –– PerPer statementstatement :: thethe triggertrigger bodybody executesexecutes onceonce forfor thethe triggeringtriggering event.event. ThisThis isis thethe default.default. –– ForFor eacheach rowrow :: thethe triggertrigger bodybody executesexecutes onceonce forfor eacheach rowrow affectedaffected byby thethe triggeringtriggering event.event. WhenWhen thethe triggertrigger cancan bebe firedfired –– RelativeRelative toto thethe executionexecution ofof anan SQLSQL DMLDML statementstatement (before(before oror afterafter oror insteadinstead ofof it)it) –– ExactlyExactly inin aa situationsituation dependingdepending onon specificspecific systemsystem resourcesresources (e.g.(e.g. signalsignal fromfrom thethe systemsystem clock,clock, expiringexpiring timer,timer, exhaustingexhausting memory)memory)

40 Example:Example: RegisteringRegistering OperationsOperations

SQL>SQL> CREATECREATE TRIGGERTRIGGER increase_salary_trgincrease_salary_trg 22 BEFORE BEFORE UPDATEUPDATE OFOF salsal 33 ON ON empemp 44 BEGINBEGIN 55 INSERTINSERT INTOINTO sal_hist(increasedsal_hist(increased,, changedOn)changedOn) 66 VALUES VALUES ( (‘YES’,‘YES ’, SYSDATE);SYSDATE); 77 END;END; 88 / /

Trigger name: increase_salary_trg Timing: BEFORE executing the statement Triggering event: UPDATE of sal Target: emp table

Trigger action: INSERT values INTO sal_hist table 41 AnotherAnother TriggerTrigger ExampleExample

CREATE TRIGGER YoungSailorUpdate AFTER INSERT ON SAILORS REFERENCING NEW TABLE AS NewSailors FOR EACH STATEMENT

INSERT INTO YoungSailors (sid , name, age, rating) SELECT sid , name, age, rating FROM NewSailors N WHERE N.age <= 18 SyntaxSyntax forfor CreatingCreating RowRow TriggersTriggers CREATECREATE [OR[OR REPLACE]REPLACE] TRIGGERTRIGGER trigger_nametrigger_name timingtiming event1event1 [ [ OROR event2event2 OROR event3]event3] ONON table_nametable_name [REFERENCING[REFERENCING OLDOLD ASAS oldold || NEWNEW ASAS newnew ]] FORFOR EACHEACH ROWROW [WHEN[WHEN conditioncondition ]] BEGINBEGIN SQLSQL statements;statements; ENDEND

The trigger body consisting of SQL statements will be executed once for each rowaffected by event1(event2, event3) in the table named table_namesubject to the additional condition.

43 ExampleExample TriggerTrigger

AssumeAssume ourour DBDB hashas aa relationrelation schemaschema :: ManagerManager (Num,(Num, Name,Name, salary)salary) WeWe wantwant toto writewrite aa triggertrigger thatthat :: EnsuresEnsures thatthat anyany newnew managermanager insertedinserted hashas :: salarysalary >=>= 6000060000

44 ExampleExample TriggerTrigger

CREATECREATE TRIGGERTRIGGER minSalaryminSalary BEFOREBEFORE INSERTINSERT ONON MANAGERMANAGER forfor whatwhat contextcontext ?? BEGINBEGIN

checkcheck forfor violationviolation herehere

END;END;

45 ExampleExample TriggerTrigger

CREATECREATE TRIGGERTRIGGER minSalaryminSalary BEFOREBEFORE INSERTINSERT ONON ManagerManager FORFOR EACHEACH ROWROW BEGIN

CheckCheck Violation of Minimum Manager Salary

END;

46 ExampleExample TriggerTrigger

CREATE TRIGGER minSalary BEFORE INSERT ON Manager FOR EACH ROW BEGIN IF (:new.salary < 60000) THEN RAISE_APPLICATION_ERROR ( -20004, ‘Violation of Minimum Manager Salary ’); END IF; END;

47 DetailsDetails ofof TriggerTrigger ExampleExample

BEFORE INSERT ON Manager – This trigger is checked before the tuple is inserted in the Target Table Manager FOR EACH ROW – specifies that trigger is performed for each row inserted :new – :new variable refers to the new tuple inserted If (:new.salary < 60000) – then an application error is raised and hence the row is not inserted; otherwise the row is inserted.

48 ExampleExample triggertrigger

CREATE TRIGGER minSalary BEFORE INSERT ON Manager FOR EACH ROW DECLARE temp int ; -- dummy variable for example BEGIN IF (:new.salary < 60000) THEN RAISE_APPLICATION_ERROR ( -20004, ‘Violation of Minimum Manager Salary ’); END IF; temp := 10 ; -- to illustrate declared variables END;

49 ExampleExample TriggerTrigger UsingUsing ConditionCondition CREATE TRIGGER minSalary BEFORE INSERT ON Manager FOR EACH ROW WHEN (new.salary < 60000) BEGIN RAISE_APPLICATION_ERROR ( -20004, ‘Violation of Minimum Manager Salary ’); END; Conditions can refer to old/new values of tuples modified by the statement (Event) activating the trigger.

50 Triggers:Triggers: REFERENCINGREFERENCING

CREATECREATE TRIGGERTRIGGER minSalaryminSalary BEFOREBEFORE INSERTINSERT ONON ManagerManager REFERENCINGREFERENCING NEWNEW asas newTuplenewTuple FORFOR EACHEACH ROWROW WHENWHEN (( newTuplenewTuple .salary.salary << 60000)60000) BEGINBEGIN RAISE_APPLICATION_ERRORRAISE_APPLICATION_ERROR (( --20004,20004, ‘‘ViolationViolation ofof MinimumMinimum ManagerManager SalarySalary ’’);); END;END;

51 DetailsDetails ofof TriggerTrigger ExampleExample

BEFORE UPDATE ON Emp – This trigger is checked before the tuple is updated in the Target Table Emp FOR EACH ROW – specifies that trigger is performed for each row inserted :new, :old – :new variable refers to the new tuple after update – :old variable refers to the old tuple before update If (:new.salary < :old.salary ) – then an application error is raised and hence the row is not updated; otherwise the row is updated. 52 ExampleExample TriggerTrigger

EnsureEnsure thatthat salarysalary doesdoes notnot decreasedecrease

CREATE TRIGGER minSalary BEFORE UPDATE ON Manager REFERENCING OLD AS oldTuple NEW as newTuple FOR EACH ROW WHEN ( newTuple.salary < oldTuple.salary ) BEGIN RAISE_APPLICATION_ERROR ( -20004, ‘Salary Decreasing !! ’); END;

53 ExampleExample TriggerTrigger

EnsureEnsure thatthat salarysalary doesdoes notnot decreasedecrease CREATE TRIGGER minSalary BEFORE UPDATE ON Emp FOR EACH ROW

BEGIN IF (: new.salary < :old.salary ) THEN RAISE_APPLICATION_ERROR ( -20004, ‘Violation of Salary Increase ’); END IF;

END;

54 RowRow vsvs StatementStatement LevelLevel TriggerTrigger

RowRow level:level: activatedactivated onceonce perper modifiedmodified tupletuple StatementStatement level:level: activateactivate onceonce perper SQLSQL statementstatement RowRow levellevel triggerstriggers cancan accessaccess newnew data,data, statementstatement levellevel triggerstriggers cannotcannot alwaysalways dodo thatthat (depends(depends onon DBMS).DBMS). StatementStatement levellevel triggerstriggers willwill bebe moremore efficientefficient ifif wewe dodo notnot needneed toto makemake rowrow -- specificspecific decisionsdecisions

55 EventEvent forfor StatementStatement andand RowRow TriggersTriggers Example 1: Monitoring Statement Events

SQL>SQL> INSERTINSERT INTOINTO deptdept (deptno,(deptno, dname,dname, loc)loc) 22 VALUESVALUES (50,(50, 'EDUCATION','EDUCATION', 'NEW'NEW YORK');YORK');

Execute only once per event even if multiple rows affected

Example 2: Monitoring Row Events

SQL>SQL> UPDATEUPDATE empemp 22 SETSET salsal == salsal ** 1.11.1 33 WHEREWHERE deptnodeptno == 30;30; Execute for each row of the table affected by the event 56 FiringFiring SequenceSequence ofof DatabaseDatabase TriggersTriggers onon aa SingleSingle RowRow

DEPT table BEFORE Statement trigger

DEPTNO DNAME LOC 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS BEFORE Row trigger 30 SALES CHICAGO 40 OPERATIONS BOSTON AFTER Row trigger

AFTER Statement trigger

57 FiringFiring SequenceSequence ofof DatabaseDatabase TriggersTriggers onon MultipleMultiple RowsRows

EMP table BEFORE statement trigger

EMPNO ENAME DEPTNO BEFORE row trigger 7839 KING 30 AFTER row trigger 7698 BLAKE 30 BEFORE row trigger AFTER row trigger 7788 SMITH 30 BEFORE row trigger AFTER row trigger

AFTER statement trigger

58 Example:Example: CalculatingCalculating DerivedDerived ColumnsColumns

SQL>CREATESQL>CREATE OROR REPLACEREPLACE TRIGGERTRIGGER derive_commission_trgderive_commission_trg 22 BEFOREBEFORE UPDATEUPDATE OFOF salsal ONON empemp 33 FORFOR EACHEACH ROWROW 44 WHENWHEN (new.job(new.job == 'SALESMAN')'SALESMAN') 55 BEGINBEGIN 66 :new.comm:new.comm := := :old.comm:old.comm * * (:new.sal/:old.sal);(:new.sal/:old.sal); 77 END;END; 88 / /

Trigger name: derive_commission_trg Timing: BEFORE executing the statement Triggering event: UPDATE of sal column Note: no (colon : ) before Filtering condition: job = ‘SALESMAN’ new in WHEN Target: emp table Trigger parameters: old, new Trigger action: calculate the new commission to be updated 59 TriggerTrigger ExecutionExecution orderorder

1. Execute all BEFORE STATEMENT triggers 2. Disable temporarily all integrity constraints recorded against the table 3. Loop for each row in the table – Execute all BEFORE ROW triggers – Execute the SQL statement against the row and perform integrity constraint checking of the data – Execute all AFTER ROW triggers 4. Complete deferred integrity constraint checking against the table 5. Execute all AFTER STATEMENT triggers

60 CursorsCursors

YouYou cancan declaredeclare aa cursorcursor onon aa tabletable oror queryquery statementstatement (which(which generatesgenerates aa tabletable asas aa result).result). YouYou cancan openopen aa cursor,cursor, andand repeatedlyrepeatedly fetchfetch aa tupletuple thenthen movemove thethe cursor,cursor, untiluntil allall tuplestuples havehave beenbeen retrieved.retrieved. YouYou cancan modify/deletemodify/delete aa tupletuple pointedpointed toto byby aa cursor.cursor. SQLSQL mustmust bebe ableable toto reportreport datadata --generatedgenerated errors.errors. CursorsCursors

CursorCursor pointspoints toto thethe currentcurrent row.row.

DECLAREDECLARE cNamecName CURSORCURSOR FORFOR selectselect statementstatement –– declaresdeclares thethe selectselect statementstatement OPENOPEN cNamecName –– ExecutesExecutes thethe selectselect statementstatement

62 EmbeddingEmbedding SQLSQL inin C:C: AnAn ExampleExample

Void ListAges ( int minzip ) { char SQLSTATE[6];

EXEC SQL BEGIN DECLARE SECTION char c_name[20]; char c_party[3]; integer minzip ; EXEC SQL END DECLARE SECTION

• SQLSTATE holds SQL error codes • EXEC SQL denotes embedded SQL section • DECLARE SECTION binds variables into SQL CursorCursor thatthat getsgets namesnames ofof candidatescandidates whowho havehave aa principalprincipal committee,committee, inin alphabeticalalphabetical orderorder

EXEC SQL DECLARE cinfo CURSOR FOR SELECT N.Candname FROM Cand N JOIN Comm M ON ( N.Princomm = M.Commid ) ORDER BY N.Candname ;

OPEN cinfo ;

FETCH cinfo INTO :c -name ; (probably in a loop in your program) CLOSE cinfo ; Notice the colon in :cname – it refers to a variable that has been declared in the surrounding program EmbeddingEmbedding inin C:C: AnAn ExampleExample

EXEC SQL DECLARE cinfo CURSOR FOR SELECT N. candname , N.par FROM cand N WHERE zip > : minzip ORDER BY N.candname ;

DECLARE cinfo CURSOR: defines a name for Cursor SELECT … : SQL whose results the cursor will point to :minzip : Note the colon referring to a C variable declared previously

65 EmbeddingEmbedding inin C:C: AnAn ExampleExample

EXEC SQL OPEN cinfo ; EXEC SQL FETCH cinfo INTO :c_name ; While (SQLSTATE != “02000 ”) { printf( “Candidate name is % s\n”, candname ); EXEC SQL FETCH cinfo INTO :c_name ; } ; EXEC SQL CLOSE cinfo ; OPEN cinfo : Executes the query and positions the cursor before the first row of the output FETCH cinfo INTO : assigns the data of the first row (if it exists) into C program variables CLOSE cinfo : Free the cursor ’s resources

66