views:

827

answers:

1

As an example, say I have a these tables...

person (id, currentyear)

personteam (id, workyear, team)

A person is assigned a team for each year they work at a company. 'personteam' stores a record of the teams. The insert into 'personteam' is only allowed if the 'currentyear' field in 'person' equals the 'workyear' in 'personteam'.

I want to do some checks when a user inserts into PERSON_TEAM, based on what is stored in PERSON. So I am writing a trigger with a select statement. I am not a 100% sure on the syntax of MySQL triggers so hopefully this makes sense...

CREATE TRIGGER mytesttrigger BEFORE INSERT ON personteam

FOR EACH ROW

SELECT currentyear AS @variablename
FROM person p
WHERE p.id = NEW.id

IF @variablename != NEW.workyear
ERROR

END

Could anyone provide a revised, corrected syntax for such an operation?

Thank you.

(This example is trivial so I can learn so please excuse how meaningless it may sound)

A: 

according to the mysql standard, the proper way to handle this would be the SIGNAL command to throw an error back to the client. since this is a BEFORE trigger, an error in the trigger will prevent mysql from moving on and inserting the row.

however, mysql does not yet support SIGNAL, so we have to come up with a way to cause an arbitrary error.

one way to do this is to call a non-existent procedure, as demonstrated here.

a better idea would be to remove INSERT rights from this table and instead use a stored procedure to handle the insert for you.

longneck