I have a table with a primary key (lets call it “person”), and another table that references it (lets call it “grade”, as in student grades).
Table “grade” has field “grade.personid”, which is a foreign key to “person.personid”. Lets say “person” has field “person.type” as well (varchar with possible values of “student” or “teacher” for simplicity), and only students have grades.
How do I make the database reject any inserts/updates that put the “personid” of a non-student (i.e. teacher) in the “grade.personid” field.
I’m currently working with Sql Server 2008, but would be interested in answers for other platforms too.
[ grade ]
[ person ] [--------]
[--------] [gradeid ]
[personid] <-FK- [personid]
[type ] [data ]
[name ]
p.s. I’m aware of constraints on schema bound views but don’t really like them because they break whenever anyone modifies the tables they rely on.
In case of SQL Server desired logic can be implemented by defining
INSTEAD OFtrigger. For Mysql server, for instance, you will need to defineBEFOREtrigger.UPDATE. Example of trigger(SQL server)
For mysql, it should be
CREATE TRIGGER ... BEFORE INSERT. Also, mysql doesn’t have an analogue ofRAISEERROR, so you will need to generate an error to prevent inserting. Usually, I useINSERT INTO not_existing_table(id) VALUES(1,2)to get a runtime error in a trigger body.