Add contraint that checks sum
I'm trying to add a constraint to a table by checking that the sum of a value is < 100.
This is my schema:
CREATE TABLE Works (
eid INTEGER,
did INTEGER,
pct_time INTEGER,
PRIMARY KEY (eid,did),
FOREIGN KEY (eid) REFERENCES Employee(eid),
FOREIGN KEY (did) REFERENCES Dept(did)
);
I need to check that the sum of pct_time for each eid is <= 100.
For example
eid --- did ---- pct_time
0 ----- a ------- 50
0 ----- d ------- 40
0 ----- c ------- 20
1 ----- a ------- 90
1 ----- b ------- 10
2 ----- d ------- 40
2 ----- a ------- 20
Here, it should have errored when I added the 3rd entry for eid 0 as the sum > 100.
It would have been fine for eid 1 and 2 as pct_time <= 100 How can this be done?So far all I've done is
ALTER TABLE Works
ADD CONSTRAINT c1
CHECK SU开发者_如何学JAVAM(pct_time) < 100
You should use a trigger for this. Make it check if SELECT SUM(pct_time) FROM Works GROUP BY eid
has any values that will go over 100 after your insert. If it is the case, throw an error.
Are you familiar with triggers? What database system are you using?
EDIT: Check out the documentation for triggers here. Basically what you want is something like this:
CREATE TRIGGER Work_insert_trigger
BEFORE INSERT ON Works
FOR EACH ROW
EXECUTE PROCEDURE check_sum_work();
Then your check_sum_work()
procedure will check if any SUM(pct_time) > 100.
Here is the documentation for trigger procedures, take note of the NEW
special variable which allows you to single out the element being inserted. So you'll want to SELECT SUM(pct_time) FROM Works WHERE eid = NEW.eid
and see if that sum + NEW.pct_time
is greater than 100.
This might sounds pretty complicated if you've never seen triggers before, but it's actually a pretty powerful mechanism that you'll learn to appreciate. :)
Here is another example of PostgeSQL triggers being used.
精彩评论