Ch02 Constraints Triggers View
Ch02 Constraints Triggers View
2
Declaring Foreign-Key
Constraints
In SQL we may declare an attribute or attributes of
one relation to be a foreign key, referencing some
attribute(s) of a second relation (possibly the same
relation)
The referenced attribute(s) of the second relation
must be declared UNIQUE or the PRIMARY KEY for
their relation. Otherwise, we cannot make the
foreign-key declaration.
Values of the foreign key appearing in the first
relation must also appear in the referenced attributes
of some tuple.
3
Two ways to declare a foreign key.
• Example:
Suppose we wish to declare the relation
Studio(name, address, presC#)
which has a foreign key presC# that references cert#
of relation:
MovieExec(name, addreses, cert#, netWorth)
We may declare presC# directly to reference cert# as
follows:
CREATE TABLE Studio (
name CHAR(30) PRIMARY KEY,
address VARCHAR(255),
presC# INT REFERENCES
MovieExec(cert#));
4
Two ways to declare a foreign key (cont.).
• Example:
An alternative form is to add the foreign key
declaration separately, as
CREATE TABLE Studio (
name CHAR(30) PRIMARY KEY,
address VARCHAR(255),
presC# INT,
FOREIGN KEY (presC#) REFERENCES
MovieExec(cert#)
);
5
Maintaining Referential Integrity.
• The following actions will be prevented by the DBMS
(i.e., a run-time exception or error will be generated).
a)Insert a new Studio tuple whose presC# value is not
NULL and is not the cert# component of any
MovieExec tuple.
b)Update a Studio tuple to change the presC#
component to a non-NULL value that is not the
cert# component of any MovieExec tuple.
c) Delete a MovieExec tuple, and its cert# component,
which is not NULL, appears as the presC# component
of one or more Studio tuples.
d)Update a MovieExec tuple in a way that changes the
cert# value, and the old cert# is the value of
presC# of some movie studio.
6
Maintaining Referential Integrity (cont.)
Example:
CREATE TABLE Studio (
name CHAR(30) PRIMARY KEY,
address VARCHAR(255),
presC# INT REFERENCES
MovieExec(cert#)
ON DELETE SET NULL
ON UPDATE CASCADE
);
8
Constraints on Attributes and Tuples.
Not-Null Constraints:
Example:
CREATE TABLE Studio (
name CHAR(30) PRIMARY KEY,
address VARCHAR(255),
presC# INT REFERENCES MovieExec(cert#)
NOT NULL
);
11
Modification of Constraints.
Giving Names to Constraints :
Example:
CREATE TABLE MovieStar (
name CHAR(30) CONSTRAINT NamelsKey PRIMARY KEY,
address VARCHAR(255),
gender CHAR(1),
birthdate DATE,
CONSTRAINT RightTitle
CHECK (gender = ’F’ OR name NOT LIKE ’Ms.%’ )
);
Remember, it is a good idea to give each of your
constraints a name, even if you do not believe you will
ever need to refer to it.
12
Modification of Constraints.
Altering Constraints on Tables:
Example:
ALTER TABLE MovieStar DROP CONSTRAINT
NamelsKey;
13
Triggers.
• A trigger is a series of actions that are associated with
certain events, and that are performed whenever these
events arise.
• Triggers differ from the kinds of constraints in three
points:
1. Triggers are only awakened when certain events,
specified by the database programmer, occur (usually
insert, delete, or update).
2. Once awakened by its triggering event, the trigger tests
a condition.
3. If the condition of the trigger is satisfied, the action
associated with the trigger is performed by the DBMS.
Triggers, sometimes called event-condition-action
rules or ECA rules
14
Triggers.
• Example. MovieExec(name, address, cert#,
netWorth)
1) CREATE TRIGGER NetWorthTrigger
2) AFTER UPDATE OF netWorth ON MovieExec
3) REFERENCING
4) OLD ROW AS OldTuple,
5) NEW ROW AS NewTuple
6) FOR EACH ROW
7) WHEN (OldTuple.netWorth > NewTuple.netWorth)
8) UPDATE MovieExec
9) SET netWorth = OldTuple.netWorth
10) WHERE cert# = NewTuple.cert#;
15
The Options for Trigger Design
17
The Options for Trigger Design
• Example
1) CREATE TRIGGER AvgNetWorthTrigger
2) AFTER UPDATE OF netWorth ON MovieExec
3) REFERENCING
4) OLD TABLE AS OldStuff,
5) NEW TABLE AS NewStuff
6) FOR EACH STATEMENT
7) WHEN ((SELECT AVG(netWorth) FROM MovieExec) < 500000 )
8) BEGIN
9) DELETE FROM MovieExec
10) WHERE (name, address , cert#, netWorth) IN NewStuff;
11) INSERT INTO MovieExec
12) (SELECT * FROM OldStuff ) ;
13) END;
18
Create trigger in SQL server
CREATE TRIGGER Trigger_name ON {table | View}
{FOR | AFTER | INSTEAD OF} { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
AS { sql_statement [ ; ] [ ,...n ] [ ; ] > }
•Arguments
- FOR | AFTER: AFTER specifies that the DML trigger is fired only when
all operations specified in the triggering SQL statement have executed
successfully. All referential cascade actions and constraint checks also
must succeed before this trigger fires. AFTER is the default when FOR is
the only keyword specified. AFTER triggers cannot be defined on views.
- INSTEAD OF: Specifies that the DML trigger is executed instead of the
triggering SQL statement, therefore, overriding the actions of the
triggering statements. INSTEAD OF cannot be specified for DDL or logon
triggers. At most, one INSTEAD OF trigger per INSERT, UPDATE, or
DELETE statement can be defined on a table or view. INSTEAD OF
triggers are not allowed on updatable views that use WITH CHECK
OPTION.
- DML triggers are frequently used for enforcing business rules and data
19
integrity.
Create trigger in SQL server
• Example 1
The following DML trigger prints a message to the client when
anyone tries to add or change data in the Customertable in
the AdventureWorks2012 database.
20
Create trigger in SQL server
• Example 2
The following example sends an e-mail message to a specified
person (MaryM) when the Customer table changes.
23
Views
Declare by:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition;
Drop by:
DROP VIEW <name>
Modify by:
ALTER VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition; 24
Our Running Example
Beers(Beername, manf)
Bars(Barname, addr, license)
Drinkers(Drname, addr, phone)
Likes(Drname, beer)
Sells(barname, beer, price)
Frequents(Drname, barname)
Underline = key (tuples cannot have
the same value in all key attributes).
25
Example: View Definition
CanDrink(drinker, beer) is a view “containing”
the drinker-beer pairs such that the drinker
frequents at least one bar that serves the beer:
27
Views
Problem: each time a base table changes,
the view may change.
Note: A view always shows up-to-date data!
The database engine recreates the data,
using the view's SQL statement, every time a
user queries a view.
28
Un-updatable Views
Views defined using groups and aggregate functions
are not updateable
Views defined on multiple tables using joins are
generally not updateable
Ex. Dept(did, budget, manageid)
Works(eid, did, pct_time)
create view dd as
create view cc as
Select d.did, w.eid,
Select manageid,
w.pct_time
max(budget) as ln
from Dept d, Works w
from Dept;
where d.did = w.did;
29
Example
Movies (title, year, length, genre, studioName,
producerC#)
A view is defined as:
CREATE VIEW ParamountMovies AS
SELECT title , year
FROM Movies
WHERE studioName = ’ Paramount’ ;
Suppose we insert into view ParamountMovies
INSERT INTO ParamountMovies
VALUES(’StarTrek’ , 1979);
What happen??? 30
Triggers on Views
An INSTEAD OF trigger lets us interpret view
modifications in a way that makes sense.
Example: Dept(did, budget, manageid)
Works(eid, did, pct_time)
create view dd as
Select d.did, w.eid,
w.pct_time
from Dept d, Works w
where d.did = w.did;
32
The Trigger on views
CREATE TRIGGER InsertToView ON dd
INSTEAD OF INSERT
AS
DECLARE @sdid int, @seid int, @spct_time int
SELECT @sdid = inserted.did, @seid = inserted.eid,
@spct_time = inserted.pct_time
FROM inserted
BEGIN
INSERT INTO Dept(did) VALUES(@sdid)
INSERT INTO Works VALUES(@seid, @sdid, @spct_time)
END
33
The Trigger in SQL-Server
CREATE TRIGGER GiveRaise1 ON Emp AFTER update
AS
Declare @new numeric(18,0), @old numeric(18,0), @eid smallint
SELECT @new=ne.Salary, @old=ol.salary, @eid = ne.eid
FROM Inserted ne, Deleted ol
where ne.eid = ol.eid
If @new>@old BEGIN
update Emp
Set Emp.salary = @new
where Emp.salary < @new and Emp.eid in
( Select D.manageid
From Emp E, Works W, Dept D
where E.eid = @eid
and E.eid = W.eid 34
and W.did = D.did); END
Q&A
35