[英]Setting Up MySQL Triggers
I've been hearing about triggers, and I have a few questions. 我听说过触发器,我有几个问题。
What are triggers? 什么是触发器?
How do I set them up? 我该如何设置它们?
Are there any precautions, aside from typical SQL stuff, that should be taken? 除了典型的SQL内容之外,是否应该采取任何预防措施?
Triggers allow you to perform a function in the database as certain events happen (eg, an insert into a table). 触发器允许您在某些事件发生时在数据库中执行功能(例如,插入表中)。
I can't comment on mysql specifically. 我不能具体评论mysql。
Precaution: Triggers can be very alluring, when you first start using them they seem like a magic bullet to all kinds of problems. 注意事项:触发器非常诱人,当你第一次开始使用它们时,它们似乎是解决各种问题的灵丹妙药。 But, they make "magic" stuff happen, if you don't know the database inside out, it can seem like really strange things happen (such as inserts into other tables, input data changing, etc).
但是,它们会让“神奇”的东西发生,如果你不知道数据库里面的东西,它看起来真的很奇怪(例如插入其他表,输入数据变化等)。 Before implementing things as a trigger I'd seriously consider instead enforcing the use of an API around the schema (preferably in the database, but outside if you can't).
在将事物作为触发器实现之前,我会认真考虑在模式周围强制使用API(最好是在数据库中,但如果不能,则在外部)。
Some things I'd still use triggers for 我仍然使用的一些东西触发
Things you wouldn't want to use triggers for 你不想使用的东西触发器
From dev.mysql.com , a trigger is 从dev.mysql.com ,触发器是
...a named database object that is associated with a table and that is activated when a particular event occurs for the table.
...与表关联的已命名数据库对象,在表发生特定事件时激活该对象。
The syntax to create them is also documented at that site . 创建它们的语法也记录在该站点 。
Briefly, 简单地说,
CREATE
[DEFINER = { user | CURRENT_USER }]
TRIGGER trigger_name trigger_time trigger_event
ON tbl_name FOR EACH ROW trigger_stmt
And they provide an example: 他们提供了一个例子:
CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));
CREATE TRIGGER ins_sum BEFORE INSERT ON account FOR EACH ROW SET @sum = @sum + NEW.amount;
You at least need to abide by all the restrictions on stored functions . 您至少需要遵守存储函数的所有限制 。 You won't be able to lock tables, alter views, or modify the table that triggered the trigger.
您将无法锁定表,更改视图或修改触发触发器的表。 Also triggers may cause replication problems .
触发器也可能导致复制问题 。
This question is old and other answers are very good, but since the user asked about precautions that should be taken, I want to add something: 这个问题很老,其他答案都很好,但由于用户询问应该采取的预防措施,我想补充一些内容:
A trigger is a named database object that is associated with a table and that is activated when a particular event occurs for the table. 触发器是一个命名的数据库对象,它与表关联,并在表发生特定事件时激活。
To create a trigger: 要创建触发器:
CREATE TRIGGER triggerName [BEFORE|AFTER] [INSERT|UPDATE|DELETE|REPLACE] ON tableName FOR EACH ROW SET stuffToDoHERE;
Even though I answered this part the other question still stands. 即使我回答了这一部分,另一个问题仍然存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.