Assertions and Triggers
Assertions and Triggers
Assertions and Triggers
Language
(Sequel)
Chapter 5
(cont.)
More on SQL
Constraints
Triggers
Integrity Constraints
(Review)
Types of ICs:
Fundamental:
Domain constraints, primary key
constraints, foreign key constraints
General constraints : Check Constraints, Table Constraints
and Assertions.
3
10 ))
CREATE TABLE
Table Constraints
Assertions
( Constraints
over
Number of boats
CREATE TABLE
SailorsMultiple
plus number of
( sid INTEGER,
sailors is < 100
CHAR(10),
Relations) sname
rating INTEGER,
ASSERTION
not
associated
with either
table.
age REAL,
PRIMARY KEY (sid),
CHECK
( (SELECT COUNT (S.sid) FROM Sailors S)
+ (SELECT COUNT (B.bid) FROM Boats B) < 100 )
Three parts:
Semantics:
When event occurs, and condition is satisfied, the
action is performed.
10
Triggers
Event,Condition,Action
Events could be :
Example Trigger
Assume our DB has a relation schema :
Professor (pNum, pName, salary)
We want to write a trigger that :
Ensures that any new professor
inserted
has salary >= 60000
12
Example Trigger
CREATE TRIGGER minSalary BEFORE INSERT ON Professor
for what context
BEGIN
check for violation here ?
END;
13
Example Trigger
CREATE TRIGGER minSalary BEFORE INSERT ON Professor
FOR EACH ROW
BEGIN
Violation of Minimum Professor Salary?
END;
14
Example Trigger
CREATE TRIGGER minSalary BEFORE INSERT ON Professor
FOR EACH ROW
BEGIN
IF (:new.salary < 60000)
THEN RAISE_APPLICATION_ERROR (-20004,
Violation of Minimum Professor Salary);
END IF;
END;
15
Example trigger
CREATE TRIGGER minSalary BEFORE INSERT ON Professor
FOR EACH ROW
DECLARE temp int;
BEGIN
IF (:new.salary < 60000)
THEN RAISE_APPLICATION_ERROR (-20004,
Violation of Minimum Professor Salary);
END IF;
temp := 10;
END;
.
run;
16
:new
refers to the new tuple inserted
18
Triggers: REFERENCING
CREATE TRIGGER minSalary BEFORE INSERT ON Professor
REFERENCING NEW as newTuple
FOR EACH ROW
WHEN (newTuple.salary < 60000)
BEGIN
RAISE_APPLICATION_ERROR (-20004,
Violation of Minimum Professor Salary);
END;
.
run;
19
Example Trigger
CREATE TRIGGER minSalary
BEFORE UPDATE ON Professor
REFERENCING OLD AS oldTuple NEW as newTuple
FOR EACH ROW
WHEN (newTuple.salary < oldTuple.salary)
BEGIN
RAISE_APPLICATION_ERROR (-20004, Salary
Decreasing !!);
END;
.
run;
23
24
26
27
Alerters
Event logging for auditing
Security enforcement
Analysis of table accesses (statistics)
Workflow and business intelligence
30
Summary
31