Extension to SQL: View, Triggers, Cursor -...

66
1 1 Extension to SQL: Extension to SQL: View, Triggers, Cursor View, Triggers, Cursor SS Chung SS Chung

Transcript of Extension to SQL: View, Triggers, Cursor -...

11

Extension to SQL: Extension to SQL:

View, Triggers, CursorView, Triggers, Cursor

SS ChungSS Chung

22

Views (Virtual Tables) in SQLViews (Virtual Tables) in SQL

�� Concept of a view in SQLConcept of a view in SQL

�� Single table derived from other tablesSingle table derived from other tables

�� Considered to be a virtual tableConsidered to be a virtual table

33

Specification of Views in SQLSpecification of Views in SQL

�� CREATE VIEWCREATE VIEW commandcommand

�� Give Table (View) name, list of attribute names Give Table (View) name, list of attribute names

for the View (table), and a Query to specify the for the View (table), and a Query to specify the

contents of the Viewcontents of the View

44

Altering Existing ViewAltering Existing View

Replace ViewReplace View Existing_View_NameExisting_View_Name AsAs

SelectSelect…… FromFrom…… WhereWhere……;;

Replace ViewReplace View Works_On1 Works_On1 AsAs

Select Select FnameFname, , LnameLname, , PnoPno, , PnamePname, Hours, Hours

From From Employee, Employee, Works_OnWorks_On, Project, Project

Where Where SsnSsn = = EssnEssn and and PnoPno = = PnumberPnumber

55

Specification of Views in SQL Specification of Views in SQL

(cont(cont’’d.)d.)�� Specify SQL queries on a viewSpecify SQL queries on a view

�� View always upView always up--toto--datedate

�� Responsibility of the DBMS and not the user Responsibility of the DBMS and not the user

�� DROP VIEWDROP VIEW command command

�� Dispose of a viewDispose of a view

66

ViewsViews

Students (Students (sidsid, name, address, , name, address, gpagpa))

Completed ( Completed ( sidsid, course, course, grade), grade)

A A viewview is a query stored in the databaseis a query stored in the database

–– Think of it as a table definition for future useThink of it as a table definition for future use

Example view definition:Example view definition:

CREATE VIEW CREATE VIEW GSGStudentstudents AS AS

SELECT *SELECT *

FROM StudentsFROM Students

WHERE WHERE gpagpa >= 2.5>= 2.5

Views can be used like Views can be used like base tablesbase tables, in any query or in , in any query or in

any other view. Like a Macro. Different from Insert any other view. Like a Macro. Different from Insert

INTO.INTO.

77

Example view use: simpler Example view use: simpler

queriesqueries

Suppose you want to retrieve good students Suppose you want to retrieve good students

who have completed CIS430.who have completed CIS430.

GSGStudentstudents ((sidsid, name, address, , name, address, gpagpa))

SELECT S.name, SELECT S.name, S.phoneS.phone

FROM FROM GstudentsGstudents SS INNER JOIN Completed C INNER JOIN Completed C

ON ON S.sidS.sid = = C.sidC.sid

WHERE WHERE C.courseC.course = = ‘‘CIS430CIS430’’;;

ItIt’’s easier to write the query using the view.s easier to write the query using the view.

88

Views for SecurityViews for Security

This is the student table without the This is the student table without the gpagpa

field to hide field to hide gpagpa to any user in DB.to any user in DB.

CREATE VIEW CREATE VIEW SstudentsSstudents AS AS

SELECT SELECT sidsid, name, address, name, address

FROM studentsFROM students

99

Views for ExtensibilityViews for Extensibility

An An oldold companycompany’’s database includes a table: s database includes a table:

Part (Part (PartIDPartID, Name, Weight), Name, Weight)

Weight is stored in poundsWeight is stored in pounds

The company is purchased by a The company is purchased by a newnew firm that uses firm that uses

metric weightsmetric weights

The The twotwo databases, databases, old and newold and new, must be integrated and , must be integrated and

use Kg.use Kg.

But thereBut there’’s s lotslots of old software using pounds.of old software using pounds.

Solution: views!Solution: views!

1010

Views for extensibility (Views for extensibility (ctdctd))

Solution:Solution:

1.1. Base table with kilograms: Base table with kilograms: NewPartNewPart for for

newnew integrated companyintegrated company

2.2. CREATE VIEWCREATE VIEW PartPart ASAS

SELECT SELECT PartIDPartID, Name,, Name,

2.2046*2.2046*Weight Weight

FROMFROM NewPartNewPart;;

3.3. Old Old programs still call the table programs still call the table ““PartPart””

1111

Clause Clause WITH CHECK OPTION WITH CHECK OPTION

�� Must be added at the end of the view definition Must be added at the end of the view definition

if a view is to be updatedif a view is to be updated

InIn--line view (dynamic Table)line view (dynamic Table)�� Defined in the Defined in the FROMFROM clause of an SQL queryclause of an SQL query

View Update and Inline ViewsView Update and Inline Views

1212

View Implementation, View View Implementation, View

Update, and Inline ViewsUpdate, and Inline Views�� Complex problem of efficiently Complex problem of efficiently

implementing a view for queryingimplementing a view for querying

�� Query modification Query modification approachapproach

�� Modify view query into a query on underlying Modify view query into a query on underlying

base tablesbase tables

�� Disadvantage: inefficient for views defined via Disadvantage: inefficient for views defined via

complex queries that are timecomplex queries that are time--consuming to consuming to

executeexecute

1313

View ImplementationView Implementation

�� View materialization approachView materialization approach

�� Physically create a temporary view table when Physically create a temporary view table when

the view is first queried the view is first queried

�� Keep that table on the assumption that other Keep that table on the assumption that other

queries on the view will followqueries on the view will follow

�� Requires efficient strategy for automatically Requires efficient strategy for automatically

updating the view table when the base tables updating the view table when the base tables

are updatedare updated

1414

View Implementation (contView Implementation (cont’’d.)d.)

�� Incremental update strategiesIncremental update strategies

�� DBMS determines what new DBMS determines what new tuplestuples must be must be

inserted, deleted, or modified in a materialized inserted, deleted, or modified in a materialized

view tableview table

1515

Problem with views: updateProblem with views: update

Views cannot always be updated unambiguously. Consider Views cannot always be updated unambiguously. Consider

EmpEmpEmpEmpEmpEmpEmpEmp ((((((((empidempidempidempidempidempidempidempid, , , , , , , , enameenameenameenameenameenameenameename, address, , address, , address, , address, , address, , address, , address, , address, deptiddeptiddeptiddeptiddeptiddeptiddeptiddeptid))))))))Dept (Dept (Dept (Dept (Dept (Dept (Dept (Dept (deptiddeptiddeptiddeptiddeptiddeptiddeptiddeptid, , , , , , , , dnamednamednamednamednamednamednamedname))))))))CREATE VIEW CREATE VIEW CREATE VIEW CREATE VIEW CREATE VIEW CREATE VIEW CREATE VIEW CREATE VIEW EMPDEPTEMPDEPTEMPDEPTEMPDEPTEMPDEPTEMPDEPTEMPDEPTEMPDEPT ASASASASASASASASSELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT enameenameenameenameenameenameenameename, , , , , , , , dnamednamednamednamednamednamednamednameFROM FROM FROM FROM FROM FROM FROM FROM EmpEmpEmpEmpEmpEmpEmpEmp InnerJOINInnerJOINInnerJOINInnerJOINInnerJOINInnerJOINInnerJOINInnerJOIN Dept ON Dept ON Dept ON Dept ON Dept ON Dept ON Dept ON Dept ON Emp.deptidEmp.deptidEmp.deptidEmp.deptidEmp.deptidEmp.deptidEmp.deptidEmp.deptid========Dept.deptidDept.deptidDept.deptidDept.deptidDept.deptidDept.deptidDept.deptidDept.deptid;;;;;;;;EMPDEPTEMPDEPTEMPDEPTEMPDEPTEMPDEPTEMPDEPTEMPDEPTEMPDEPT enameenameenameenameenameenameenameename dnamednamednamednamednamednamednamedname

jimjimjimjimjimjimjimjim shoeshoeshoeshoeshoeshoeshoeshoejoejoejoejoejoejoejoejoe suitsuitsuitsuitsuitsuitsuitsuit

I want to delete (I want to delete (jimjim, shoe) from EMPDEPT., shoe) from EMPDEPT.

Can I do that? Can I do that?

1616

View UpdateView Update

View can be updatedView can be updated ifif

–– It is defined It is defined on a single base tableon a single base table

–– Using Using only Selection and Projectiononly Selection and Projection

–– No AggregatesNo Aggregates

–– No DISTINCTNo DISTINCT

1717

View Update and Inline ViewsView Update and Inline Views

�� Update on a view defined Update on a view defined on a single table on a single table

without any aggregate functionswithout any aggregate functions

�� Can be mapped to an update on underlying Can be mapped to an update on underlying

base tablebase table

�� View involving joins can NOT be updatedView involving joins can NOT be updated

�� Often Often not possiblenot possible for DBMS to determine for DBMS to determine

which of the updates is intendedwhich of the updates is intended

1818

Levels of AbstractionLevels of Abstraction

Physical Schema

Conceptual Schema

ES 1 ES 2 ES 3

Physical storage; DBA

Logical storage; data

designer

External view; user

and data designer

1919

Physical SchemaPhysical Schema

The The physical schemaphysical schema is a description of is a description of

how the data is physically stored in the how the data is physically stored in the

database. It includesdatabase. It includes

–– Where the data is locatedWhere the data is located

–– File structuresFile structures

–– Access methodsAccess methods

–– Indexes Indexes

The physical schema is managed by the The physical schema is managed by the

DBA.DBA.

2020

Conceptual SchemaConceptual Schema

The The conceptual schemaconceptual schema

-- a logical description of how the data is a logical description of how the data is

stored. stored.

-- It consists of the schemas we have It consists of the schemas we have

described with described with CREATE TABLECREATE TABLE

statements. statements.

It is managed by the data designer.It is managed by the data designer.

2121

External SchemasExternal Schemas

Each external schema is a combination of Each external schema is a combination of

base tables and views, tailored to the base tables and views, tailored to the

needs of a single user. It is managed needs of a single user. It is managed

by the data designer and the user.by the data designer and the user.

2222

Data IndependenceData Independence

A database model possesses A database model possesses data data

independenceindependence if application programs are if application programs are

immune to changes in the conceptual and immune to changes in the conceptual and

physical schemas.physical schemas.

Why is this important? Everything changes.Why is this important? Everything changes.

How does the relational model achieve logical How does the relational model achieve logical

(conceptual) data independence?(conceptual) data independence?

–– Through viewsThrough views

–– If the conceptual schema changes, a view can If the conceptual schema changes, a view can

be defined to preserve existing applicationsbe defined to preserve existing applications

2323

Data Independence (Data Independence (ctdctd.).)

How does the relational model achieve physical data How does the relational model achieve physical data

independence?independence?

1.1. Conceptual level contains no physical infoConceptual level contains no physical info

2.2. SQL can program against the conceptual levelSQL can program against the conceptual level

–– Earlier DBMSs (network, hierarchical) did not have Earlier DBMSs (network, hierarchical) did not have

these properties.these properties.

–– Their languages had physical properties embedded Their languages had physical properties embedded

in them.in them.

That is the primary reason for the success of the That is the primary reason for the success of the

relational modelrelational model

2424

Views: SummaryViews: Summary

A view is a stored query definitionA view is a stored query definition

Views can be very usefulViews can be very useful

–– Easier query writing, security, extensibilityEasier query writing, security, extensibility

But views cannot be unambiguously But views cannot be unambiguously

updatedupdated

Three levels of abstraction in a relational Three levels of abstraction in a relational

DBMSDBMS

–– Yields data independence: logical and Yields data independence: logical and

physicalphysical

2525

Specifying Specifying

Constraints as Assertions and Constraints as Assertions and

Actions as TriggersActions as Triggers

�� CREATE ASSERTIONCREATE ASSERTION

�� Specify additional types of constraints outside Specify additional types of constraints outside

scope of builtscope of built--in relational model constraintsin relational model constraints

�� CREATE TRIGGERCREATE TRIGGER

�� Specify automatic actions that database Specify automatic actions that database

system will perform when certain events and system will perform when certain events and

conditions occurconditions occur

2626

Specifying General Constraints Specifying General Constraints

as Assertions in SQLas Assertions in SQL�� CREATE ASSERTIONCREATE ASSERTION

�� Specify a query that selects any Specify a query that selects any tuplestuples that that

violate the desired conditionviolate the desired condition

�� Use only in cases where it is not possible to Use only in cases where it is not possible to use use CHECKCHECK on attributes and domainson attributes and domains

Assertions: Assertions:

Constraints over Multiple RelationsConstraints over Multiple Relations

CREATE TABLE Sailors( sid INTEGER,sname CHAR(10),rating INTEGER,age REAL,PRIMARY KEY (sid),CHECK

( (SELECT COUNT (S.sid) FROM Sailors S)

+ (SELECT COUNT (B.bid) FROM Boats B) < 100 )

ASSERTION ASSERTION

Not Not

associated associated

with either with either

table.table.CREATE ASSERTION smallClubCHECK

( (SELECT COUNT (S.sid) FROM Sailors S)+ (SELECT COUNT (B.bid) FROM Boats B) < 100 )

Number of boatsplus number of sailors is < 100

2828

Assertions:Assertions: Check over several tablesCheck over several tables

Any logical Any logical

expression expression

involving an SQL involving an SQL

statement can be statement can be

used to constrain used to constrain

tables in the tables in the

database.database.

CREATE ASSERTION Salary_Mgr

CHECK (NOT EXISTS

(SELECT *

FROM Employee E,

Employee M

WHERE E.salary >

M.salary AND

E.mgr = M.id ))

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

2929

Introduction to Triggers in SQLIntroduction to Triggers in SQL

�� CREATE TRIGGERCREATE TRIGGER statementstatement

�� Used to monitor the databaseUsed to monitor the database

�� Typical trigger has three components:Typical trigger has three components:

�� Event(sEvent(s))

�� ConditionCondition

�� ActionAction

Triggers (Active database)Triggers (Active database)

Trigger:Trigger: A procedure that starts automatically if A procedure that starts automatically if specified changes occur to the DBMSspecified changes occur to the DBMS

Analog to a "daemon" that Analog to a "daemon" that monitorsmonitors a database for a database for certain events to occurcertain events to occur

Three parts:Three parts:

–– Event Event : : activates the triggeractivates the trigger

–– Condition Condition : tests whether the triggers should run : tests whether the triggers should run [Optional][Optional]

–– ActionAction : : what happens if the trigger runswhat happens if the trigger runs

Semantics:Semantics:

–– When event occurs, and condition is satisfied, When event occurs, and condition is satisfied, the action is performed.the action is performed.

TriggersTriggers (Not a constraint)(Not a constraint)

Three parts:Three parts:

–– Event Event (activates the trigger)(activates the trigger)

This will be an This will be an insert, delete and/or updateinsert, delete and/or update to a to a

tabletable

–– ConditionCondition (tests whether the triggers should run)(tests whether the triggers should run)

A A logical statement or a querylogical statement or a query

–– ActionAction (what happens if the trigger runs)(what happens if the trigger runs)

Can execute queries, execute dataCan execute queries, execute data--definition definition

commands, transactioncommands, transaction--oriented commands, oriented commands,

and hostand host--language procedureslanguage procedures

WhenWhen does the Action execute?does the Action execute?

–– Specified with Specified with Event (BEFORE, AFTER)Event (BEFORE, AFTER)

3232

EventEvent--ConditionCondition--Action (ECA)Action (ECA)

EEvent vent occurs in databasesoccurs in databases

–– e.g. addition of a new row, deletion of a rowe.g. addition of a new row, deletion of a row

CConditionsonditions are checkedare checked

–– e.g. Is batch complete? Has student passed?e.g. Is batch complete? Has student passed?

AActionsctions are executed if conditions are satisfiedare executed if conditions are satisfied

–– e.g. send batch to supplier, congratulate studente.g. send batch to supplier, congratulate student

3333

Triggers Triggers –– Event,Condition,ActionEvent,Condition,Action

EventsEvents could be :could be :

BEFORE|AFTER INSERT|UPDATE|DELETE ON BEFORE|AFTER INSERT|UPDATE|DELETE ON

<<tableNametableName>>

e.g.: e.g.: BEFORE INSERT ON ManagerBEFORE INSERT ON Manager

ConditionCondition is SQL expression or even an SQL query is SQL expression or even an SQL query

(query with non(query with non--empty result means TRUE)empty result means TRUE)

Action Action can be many different choices :can be many different choices :

–– SQL statementsSQL statements

–– DDL and transactionDDL and transaction--oriented statements like oriented statements like

““commitcommit””..

3434

Trigger Syntax Trigger Syntax

CREATE TRIGGERCREATE TRIGGER <<triggerNametriggerName>>

BEFORE|AFTER BEFORE|AFTER INSERT|DELETE|UPDATE INSERT|DELETE|UPDATE

[[OFOF <<columnListcolumnList>] >] ON ON <<tableNametableName>|<>|<viewNameviewName>>

[[REFERENCING REFERENCING [[OLD ASOLD AS <<oldNameoldName>] >]

[[NEW ASNEW AS <<newNamenewName>]]>]]

[FOR EACH ROW][FOR EACH ROW]

( OR [( OR [FOR EACH STATEMENTFOR EACH STATEMENT] by default)] by default)

[WHEN (<condition>)][WHEN (<condition>)]

BeginBegin

<Trigger Action body><Trigger Action body>

End;End;

3535

Syntax for creating triggers in SQLSyntax for creating triggers in SQL

Trigger nameTrigger name -- unique within one database schemaunique within one database schema

TimingTiming -- depends on the order of controlled events depends on the order of controlled events (before or after or instead of)(before or after or instead of)

Triggering eventTriggering event -- event which fires the trigger event which fires the trigger (E)(E)

Filtering conditionFiltering condition -- checked when the triggering checked when the triggering event occurs event occurs (C)(C)

TargetTarget -- table (or view) against which the trigger is table (or view) against which the trigger is fired; they should be both created within the same fired; they should be both created within the same schemaschema

Trigger ParametersTrigger Parameters -- parameters used to denote the parameters used to denote the recordrecord columnscolumns; preceded by colon; preceded by colon

–– :new, :old:new, :old for new and old versions of the values for new and old versions of the values respectivelyrespectively

Trigger actionTrigger action -- SQL statements, executed when the SQL statements, executed when the trigger fires; surrounded by trigger fires; surrounded by BeginBegin ... ... End (A)End (A)

3636

Syntax for Creating Statement Syntax for Creating Statement

TriggersTriggers

CREATE [OR REPLACE] TRIGGER trigger_name

timing event1 [OR event2 OR event3]

ON table_name

BEGIN

SQL statements;

END;

CREATE [OR REPLACE] TRIGGER CREATE [OR REPLACE] TRIGGER trigger_nametrigger_name

timing event1 [timing event1 [OROR event2 event2 OROR event3]event3]

ONON table_name table_name

BEGINBEGIN

SQL statements;SQL 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.

Triggers: Example*Triggers: Example*Assume one donation has been inserted to Assume one donation has been inserted to indivindiv, for , for simplicitysimplicity

CREATE TRIGGERCREATE TRIGGER MYTRIG1 MYTRIG1 BEFORE INSERTBEFORE INSERT ONON AccountAccountFOR EACH STATEMENTFOR EACH STATEMENT ((------> is default) > is default) BEGINBEGIN

IF IF (TO_CHAR (SYSDATE, (TO_CHAR (SYSDATE, ’’dydy’’ ) IN ) IN ((‘‘SatSat’’, , ’’SunSun’’)) )) OR TO_CHAR (SYSDATE, OR TO_CHAR (SYSDATE, ’’hh24:mihh24:mi’’ ) )

NOT BETWEEN NOT BETWEEN ’’08:0008:00’’ AND AND ’’17:0017:00’’) )

THENTHENRAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR(--20500, 20500, ’’Cannot Cannot

create new account now !!create new account now !!’’) ;) ;

END IF;END IF;

END;END;

3838

Triggers Triggers vsvs ConstraintsConstraints

Triggers are harder to understandTriggers are harder to understand

–– If multiple triggers apply, their order of execution is If multiple triggers apply, their order of execution is

unspecifiedunspecified

–– One trigger can activate another, causing a chain of One trigger can activate another, causing a chain of

actionsactions

–– A trigger can activate itselfA trigger can activate itself

Triggers are more powerful than constraintsTriggers are more powerful than constraints

–– They can make changes to tablesThey can make changes to tables

–– They can take action before or after a data They can take action before or after a data

modificationmodification

3939

Variations in DBMS Variations in DBMS Example:TriggersExample:Triggers in SQL Serverin SQL Server

An SQL Server An SQL Server triggertrigger is a T/SQL procedure that is is a T/SQL procedure that is invoked when a specified database activity occursinvoked when a specified database activity occurs

Triggers can be used to:Triggers can be used to:

–– Enforce business rulesEnforce business rules

–– Set complex default valuesSet complex default values

–– Update viewsUpdate views

–– Implement referential integrity actionsImplement referential integrity actions

SQL Server only supports SQL Server only supports INSTEAD OFINSTEAD OF and and AFTERAFTERtriggers:triggers:

–– A A tabletable may have one or more AFTER triggers may have one or more AFTER triggers

–– AFTER triggers may AFTER triggers may notnot be assigned to be assigned to viewsviews

–– A A viewview or or tabletable may have only one INSTEAD OF may have only one INSTEAD OF trigger for each triggering actiontrigger for each triggering action

Triggers can roll back the transactions that caused them Triggers can roll back the transactions that caused them to be firedto be fired

4040

Types of SQL TriggersTypes of SQL TriggersHow many times should the trigger body execute How many times should the trigger body execute when the triggering event takes place?when the triggering event takes place?

–– Per statementPer statement:: the trigger body executes once the trigger body executes once for the triggering event. This is the default.for the triggering event. This is the default.

–– For each rowFor each row:: the trigger body executes once the trigger body executes once for each row affected by the triggering event.for each row affected by the triggering event.

When the trigger can be firedWhen the trigger can be fired

–– Relative to the execution of an SQL DML Relative to the execution of an SQL DML statement (before or after or instead of it)statement (before or after or instead of it)

–– Exactly in a situation depending on specific Exactly in a situation depending on specific system resources (e.g. signal from the system system resources (e.g. signal from the system clock, expiring timer, exhausting memory)clock, expiring timer, exhausting memory)

4141

Example: Registering OperationsExample: Registering Operations

SQL> CREATE TRIGGER increase_salary_trg

2 BEFORE UPDATE OF sal

3 ON emp

4 BEGIN

5 INSERT INTO sal_hist(increased, changedOn)

6 VALUES (‘YES’, SYSDATE);

7 END;

8 /

SQL> CREATE TRIGGER SQL> CREATE TRIGGER increase_salary_trgincrease_salary_trg

2 2 BEFORE UPDATE OF BEFORE UPDATE OF salsal

3 3 ON empON emp

4 BEGIN4 BEGIN

5 INSERT INTO 5 INSERT INTO sal_hist(increasedsal_hist(increased, changedOn), changedOn)

6 6 VALUES (VALUES (‘‘YESYES’’, SYSDATE);, SYSDATE);

7 END;7 END;

8 /8 /

Trigger name: increase_salary_trgTiming: BEFORE executing the statement

Triggering event: UPDATE of sal column

Target: emp tableTrigger action: INSERT values INTO sal_hist table

Another Trigger ExampleAnother Trigger Example

CREATE TRIGGERCREATE TRIGGER YoungSailorUpdateYoungSailorUpdate

AFTER INSERT ONAFTER INSERT ON SAILORSSAILORS

REFERENCING NEW TABLE ASREFERENCING NEW TABLE AS NewSailorsNewSailors

FOR EACH STATEMENTFOR EACH STATEMENT

INSERT INTO INSERT INTO YoungSailorsYoungSailors ((sidsid, name, age, rating), name, age, rating)

SELECT SELECT sidsid, name, age, rating, name, age, rating

FROM FROM NewSailorsNewSailors NN

WHERE WHERE N.age N.age <= 18<= 18

4343

Syntax for Creating Row Syntax for Creating Row

TriggersTriggersCREATE [OR REPLACE] TRIGGER trigger_name

timing event1 [OR event2 OR event3]

ON table_name

[REFERENCING OLD AS old | NEW AS new]

FOR EACH ROW

[WHEN condition]

BEGIN

SQL statements;

END

CREATE [OR REPLACE] TRIGGER CREATE [OR REPLACE] TRIGGER trigger_nametrigger_name

timing event1 [timing event1 [OROR event2 event2 OROR event3]event3]

ONON table_name table_name

[REFERENCING OLD AS [REFERENCING OLD AS old | old | NEW AS NEW AS newnew]]

FOR EACH ROWFOR EACH ROW

[WHEN [WHEN conditioncondition]]

BEGINBEGIN

SQL statements;SQL statements;

ENDEND

The trigger body consisting of SQL statements will be executed once for each row affected by event1 (event2, event3) in thetable named table_name subject to the additional condition.

4444

Example TriggerExample Trigger

Assume our DB has a relation schema :Assume our DB has a relation schema :

Manager (Num, Name, salary)Manager (Num, Name, salary)

We want to write a trigger that :We want to write a trigger that :

Ensures that any new manager inserted Ensures that any new manager inserted

has :has :

salary >= 60000salary >= 60000

4545

Example TriggerExample Trigger

CREATE TRIGGER CREATE TRIGGER minSalaryminSalary

BEFORE INSERT ON BEFORE INSERT ON MANAGERMANAGER

for what context ?for what context ?

BEGINBEGIN

check for violation here check for violation here

END;END;

4646

Example TriggerExample Trigger

CREATE TRIGGER CREATE TRIGGER minSalaryminSalary

BEFORE INSERT ON ManagerBEFORE INSERT ON Manager

FOR EACH ROWFOR EACH ROWBEGINBEGIN

Check Check Violation of Minimum Manager SalaryViolation of Minimum Manager Salary

END;END;

4747

Example TriggerExample Trigger

CREATE TRIGGER CREATE TRIGGER minSalaryminSalary

BEFORE INSERT ON BEFORE INSERT ON Manager Manager

FOR EACH ROWFOR EACH ROW

BEGINBEGIN

IF IF (:new.salary(:new.salary < 60000)< 60000)

THEN RAISE_APPLICATION_ERROR (THEN RAISE_APPLICATION_ERROR (--20004, 20004, ‘‘Violation of Minimum Manager SalaryViolation of Minimum Manager Salary’’););

END IF;END IF;

END;END;

4848

Details of Trigger ExampleDetails of Trigger Example

BEFORE INSERT ONBEFORE INSERT ON Manager Manager

–– This trigger is checked before the This trigger is checked before the tupletuple is inserted is inserted

in the in the Target TableTarget Table Manager Manager

FOR EACH ROWFOR EACH ROW

–– specifies that trigger is performed for each row specifies that trigger is performed for each row

insertedinserted

:new:new

–– :new variable:new variable refers to the new refers to the new tupletuple insertedinserted

If If (:new.salary(:new.salary < 60000) < 60000)

–– then an application error is raised and hence the then an application error is raised and hence the

row is not inserted; otherwise the row is inserted.row is not inserted; otherwise the row is inserted.

4949

Example triggerExample trigger

CREATE TRIGGER CREATE TRIGGER minSalaryminSalary

BEFORE INSERT ON ManagerBEFORE INSERT ON Manager

FOR EACH ROWFOR EACH ROW

DECLARE DECLARE temptemp intint;; ---- dummy variable for example dummy variable for example

BEGINBEGIN

IF IF (:new.salary(:new.salary < 60000) THEN < 60000) THEN RAISE_APPLICATION_ERROR (RAISE_APPLICATION_ERROR (--20004, 20004, ‘‘Violation of Violation of

Minimum Manager SalaryMinimum Manager Salary’’););

END IF;END IF;

temptemp := 10:= 10; ; ---- to illustrate declared variablesto illustrate declared variables

END;END;

5050

Example Trigger Example Trigger

Using Using ConditionConditionCREATE TRIGGERCREATE TRIGGER minSalaryminSalary

BEFORE INSERT ONBEFORE INSERT ON ManagerManager

FOR EACH ROWFOR EACH ROW

WHENWHEN ((new.salarynew.salary < 60000)< 60000)

BEGINBEGIN

RAISE_APPLICATION_ERROR (RAISE_APPLICATION_ERROR (--20004, 20004,

‘‘Violation of Minimum Manager SalaryViolation of Minimum Manager Salary’’););

END;END;

Conditions can refer to Conditions can refer to old/new values of old/new values of tuplestuplesmodified by the statement (Event) activating the trigger.modified by the statement (Event) activating the trigger.

5151

Triggers: Triggers: REFERENCINGREFERENCING

CREATE TRIGGER CREATE TRIGGER minSalaryminSalary

BEFORE INSERT ON Manager BEFORE INSERT ON Manager

REFERENCING NEW asREFERENCING NEW as newTuplenewTuple

FOR EACH ROW FOR EACH ROW

WHEN (WHEN (newTuplenewTuple.salary.salary < 60000)< 60000)

BEGINBEGIN

RAISE_APPLICATION_ERROR (RAISE_APPLICATION_ERROR (--20004, 20004, ‘‘Violation of Minimum Manager SalaryViolation of Minimum Manager Salary’’););

END;END;

5252

Details of Trigger ExampleDetails of Trigger Example

BEFORE BEFORE UPDATEUPDATE ONON EmpEmp

–– This trigger is checked before the This trigger is checked before the tupletuple is updated is updated

in the in the Target TableTarget Table EmpEmp

FOR EACH ROWFOR EACH ROW

–– specifies that trigger is performed for each row specifies that trigger is performed for each row

insertedinserted

:new, :old:new, :old

–– :new variable:new variable refers to the refers to the new new tupletuple after updateafter update

–– :old variable:old variable refers to the refers to the old old tupletuple before updatebefore update

If If (:new.salary(:new.salary < < ::old.salaryold.salary) )

–– then an application error is raised and hence the then an application error is raised and hence the

row is not updated; otherwise the row is updated.row is not updated; otherwise the row is updated.

5353

Example TriggerExample Trigger

Ensure that salary does not decrease Ensure that salary does not decrease

CREATE TRIGGER CREATE TRIGGER minSalaryminSalary

BEFORE UPDATEBEFORE UPDATE ON Manager ON Manager

REFERENCING OLD AS REFERENCING OLD AS oldTupleoldTuple

NEW as NEW as newTuplenewTuple

FOR EACH ROW FOR EACH ROW

WHEN (WHEN (newTuple.salarynewTuple.salary < < oldTuple.salaryoldTuple.salary))

BEGINBEGIN

RAISE_APPLICATION_ERROR (RAISE_APPLICATION_ERROR (--20004, 20004, ‘‘Salary Salary Decreasing !!Decreasing !!’’););

END;END;

5454

Example TriggerExample Trigger

Ensure that salary does not decrease Ensure that salary does not decrease CREATE TRIGGER CREATE TRIGGER minSalaryminSalary

BEFORE UPDATE ON BEFORE UPDATE ON EmpEmp

FOR EACH ROWFOR EACH ROW

BEGINBEGIN

IF IF (:(:new.salarynew.salary < < ::old.salaryold.salary) THEN ) THEN RAISE_APPLICATION_ERROR (RAISE_APPLICATION_ERROR (--20004, 20004, ‘‘Violation of Violation of

Salary IncreaseSalary Increase’’););

END IF;END IF;

END;END;

5555

Row Row vsvs Statement Level TriggerStatement Level Trigger

RowRow level: activated once per modified level: activated once per modified tupletuple

StatementStatement level: activate once per SQL level: activate once per SQL statementstatement

RowRow level triggers can access new data, level triggers can access new data, statement level triggers cannot always do statement level triggers cannot always do that (depends on DBMS).that (depends on DBMS).

StatementStatement level triggers will be more level triggers will be more efficient if we do not need to make rowefficient if we do not need to make row--specific decisionsspecific decisions

5656

SQL> INSERT INTO dept (deptno, dname, loc)

2 VALUES (50, 'EDUCATION', 'NEW YORK');

SQL> INSERT INTO dept (deptno, dname, loc)

2 VALUES (50, 'EDUCATION', 'NEW YORK');

Example 1: Monitoring Statement EventsExample 1: Monitoring Statement Events

SQL> UPDATE emp

2 SET sal = sal * 1.1

3 WHERE deptno = 30;

SQL> UPDATE emp

2 SET sal = sal * 1.1

3 WHERE deptno = 30;

Example 2: Monitoring Row EventsExample 2: Monitoring Row Events

Event for Statement and Row Event for Statement and Row

TriggersTriggers

Execute for each row of the table affected by the event

Execute only once per event even if multiple rows affected

5757

DEPTNODEPTNO

1010

2020

3030

4040

DNAMEDNAME

ACCOUNTINGACCOUNTING

RESEARCHRESEARCH

SALESSALES

OPERATIONSOPERATIONS

LOCLOC

NEW YORKNEW YORK

DALLASDALLAS

CHICAGOCHICAGO

BOSTONBOSTON

DEPT tableDEPT table BEFORE Statement trigger

BEFORE Row trigger

AFTER Row trigger

AFTER Statement trigger

Firing Sequence of DatabaseFiring Sequence of Database

Triggers on a Single RowTriggers on a Single Row

5858

EMPNOEMPNO

78397839

76987698

77887788

ENAMEENAME

KINGKING

BLAKEBLAKE

SMITHSMITH

DEPTNODEPTNO

3030

3030

3030

BEFORE statement trigger

BEFORE row triggerAFTER row triggerBEFORE row triggerAFTER row triggerBEFORE row triggerAFTER row trigger

AFTER statement trigger

Firing Sequence of Database Firing Sequence of Database

Triggers on Multiple RowsTriggers on Multiple Rows

EMP tableEMP table

5959

SQL>CREATE OR REPLACE TRIGGER derive_commission_trg

2 BEFORE UPDATE OF sal ON emp

3 FOR EACH ROW

4 WHEN (new.job = 'SALESMAN')

5 BEGIN

6 :new.comm := :old.comm * (:new.sal/:old.sal);

7 END;

8 /

SQL>CREATE OR REPLACE TRIGGER derive_commission_trg

2 BEFORE UPDATE OF sal ON emp

3 FOR EACH ROW

4 WHEN (new.job = 'SALESMAN')

5 BEGIN

6 :new.comm := :old.comm * (:new.sal/:old.sal);

7 END;

8 /

Example: Calculating Derived ColumnsExample: Calculating Derived Columns

Trigger name: derive_commission_trgTiming: BEFORE executing the statementTriggering event: UPDATE of sal columnFiltering condition: job = ‘SALESMAN’Target: emp tableTrigger parameters: old, newTrigger action: calculate the new

commission to be updated

Note: no (colon : ) before

new in WHEN

6060

Trigger Execution orderTrigger Execution order

1. Execute all BEFORE STATEMENT triggers1. Execute all BEFORE STATEMENT triggers

2. Disable temporarily all integrity constraints recorded 2. Disable temporarily all integrity constraints recorded against the tableagainst the table

3. Loop for each row in the table3. Loop for each row in the table

–– Execute all BEFORE ROW triggersExecute all BEFORE ROW triggers

–– Execute the SQL statement against the row and Execute the SQL statement against the row and perform integrity constraint checking of the dataperform integrity constraint checking of the data

–– Execute all AFTER ROW triggersExecute all AFTER ROW triggers

4. 4. Complete deferred integrity constraint checking Complete deferred integrity constraint checking against the tableagainst the table

5. Execute all AFTER STATEMENT triggers5. Execute all AFTER STATEMENT triggers

CursorsCursors

You can declare a You can declare a cursorcursor on a table or query on a table or query

statement (which generates a table as a result).statement (which generates a table as a result).

You can You can openopen a cursor, and repeatedlya cursor, and repeatedly fetchfetch a a

tuple then tuple then movemove the cursor, until all the cursor, until all tuplestuples have have

been retrieved.been retrieved.

You can modify/delete a You can modify/delete a tupletuple pointed to by a pointed to by a

cursor.cursor.

SQL must be able to report dataSQL must be able to report data--generated generated

errors.errors.

6262

CursorsCursors

Cursor points to the current row.Cursor points to the current row.

DECLARE DECLARE cNamecName CURSOR CURSOR

FORFOR select statementselect statement

–– declares the select statementdeclares the select statement

OPENOPEN cNamecName

–– Executes the select statementExecutes the select statement

Embedding SQL in C: An ExampleEmbedding SQL in C: An Example

Void Void ListAgesListAges( ( intint minzipminzip))

{{

char SQLSTATE[6];char SQLSTATE[6];

EXEC SQLEXEC SQL BEGIN DECLARE SECTIONBEGIN DECLARE SECTION

charchar c_name[20]; c_name[20];

char char c_party[3]; c_party[3];

integer integer minzipminzip;;

EXEC SQLEXEC SQL END DECLARE SECTIONEND DECLARE SECTION

• SQLSTATE holds SQL error codes

• EXEC SQL denotes embedded SQL section

• DECLARE SECTION binds variables into

SQL

CursorCursor that gets names of candidates who that gets names of candidates who

have a principal committee, in alphabetical have a principal committee, in alphabetical

orderorder

EXEC SQL EXEC SQL DECLARE DECLARE cinfocinfo CURSORCURSOR FORFOR

SELECT SELECT N.CandnameN.Candname

FROM FROM CandCand N JOIN N JOIN CommComm M ON (M ON (N.PrincommN.Princomm = = M.CommidM.Commid))

ORDER BY ORDER BY N.CandnameN.Candname;;

OPEN OPEN cinfocinfo;;

FETCH FETCH cinfocinfo INTO INTO :c:c--namename; (probably in a loop in your ; (probably in a loop in your

program)program)

CLOSE CLOSE cinfocinfo;; Notice the colon in :cname – it refers to a variable that has

been declared in the surrounding program

6565

Embedding in C: An ExampleEmbedding in C: An Example

DECLAREDECLARE cinfocinfo CURSOR:CURSOR: defines a name for Cursordefines a name for Cursor

SELECT SELECT …… : SQL whose results the cursor will : SQL whose results the cursor will point topoint to

::minzipminzip : Note the colon referring to a C variable : Note the colon referring to a C variable declared previouslydeclared previously

EXEC SQL EXEC SQL DECLARE DECLARE cinfocinfo CURSOR FORCURSOR FOR

SELECT SELECT N. N. candnamecandname, , N.parN.par

FROM FROM candcand NN

WHERE WHERE zip > :zip > :minzipminzip

ORDER BY ORDER BY N.candnameN.candname;;

6666

Embedding in C: An ExampleEmbedding in C: An Example

OPENOPEN cinfocinfo : Executes the query and positions the : Executes the query and positions the cursor before the first row of the outputcursor before the first row of the output

FETCH FETCH cinfocinfo INTOINTO : assigns the data of the first row (if it : assigns the data of the first row (if it exists) into C program variablesexists) into C program variables

CLOSE CLOSE cinfocinfo : Free the cursor: Free the cursor’’s resourcess resources

EXEC SQLEXEC SQL OPENOPEN cinfocinfo;;

EXEC SQLEXEC SQL FETCHFETCH cinfocinfo INTOINTO ::c_namec_name;;

WhileWhile(SQLSTATE(SQLSTATE != != ““0200002000””) )

{{

printf(printf(““CandidateCandidate name is %name is %ss\\nn””, , candnamecandname););

EXEC SQL FETCHEXEC SQL FETCH cinfocinfo INTOINTO ::c_namec_name;;

} ;} ;

EXEC SQLEXEC SQL CLOSECLOSE cinfocinfo;;