简体   繁体   English

带有SELECT语句的MySQL Trigger

[英]MySQL Trigger with SELECT statement

As an example, say I have a these tables... 举个例子,假设我有这些表......

person (id, currentyear) 人(id,currentyear)

personteam (id, workyear, team) 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. 'personteam'存储了团队的记录。 The insert into 'personteam' is only allowed if the 'currentyear' field in 'person' equals the 'workyear' in 'personteam'. 只有当'person'中的'currentyear'字段等于'personteam'中的'workyear'时,才允许插入'personteam'。

I want to do some checks when a user inserts into PERSON_TEAM, based on what is stored in PERSON. 我希望在用户根据PERSON中存储的内容插入PERSON_TEAM时进行一些检查。 So I am writing a trigger with a select statement. 所以我用select语句编写了一个触发器。 I am not a 100% sure on the syntax of MySQL triggers so hopefully this makes sense... 我不是100%肯定MySQL触发器的语法,所以希望这是有道理的...

CREATE TRIGGER mytesttrigger BEFORE INSERT ON personteam 在插入人员队伍之前创建触发mytesttrigger

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) (这个例子很简单,所以我可以学习,请原谅这听起来多么无意义)

According to the MySQL standard, the proper way to handle this would be the SIGNAL command to throw an error back to the client. 根据MySQL标准,处理此问题的正确方法是将错误发送回客户端的SIGNAL命令。 since this is a BEFORE trigger, an error in the trigger will prevent mysql from moving on and inserting the row. 因为这是一个BEFORE触发器,触发器中的错误将阻止mysql继续前进并插入行。

However, mysql does not yet support SIGNAL, so we have to come up with a way to cause an arbitrary error. 但是,mysql还不支持SIGNAL,所以我们必须想出一种导致任意错误的方法。

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. 更好的想法是从该表中删除INSERT权限,而是使用存储过程为您处理插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM