4

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)

1
  • 1
    Now assuming... FOR EACH ROW BEGIN SET @variablename = (SELECT currentyear FROM person p WHERE p.id = NEW.id); IF @variablename != NEW.workyear THEN ERROR; ENDIF; END; Commented Oct 28, 2009 at 23:10

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.