mysql和触发器的使用问题
我遇到的情况是,如果满足特定条件,我不希望发生插入(事务应该回滚)。我可以在应用程序代码中编写此逻辑,但由于某种原因,它必须用 MySQL 本身编写(假设用不同语言编写的客户端将插入到此 MySQL InnoDB 表中)[这是一个单独的讨论]。
表定义:
CREATE TABLE table1(x int NOT NULL);
触发器看起来像这样:
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
NEW.x = NULL;
END IF;
END;
我猜它也可以写成(未经测试):
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
ROLLBACK;
END IF;
END;
但是,这不起作用:
CREATE TRIGGER t1 BEFORE INSERT ON table1 ROLLBACK;
您可以保证:
- 您的数据库将始终是 MySQL
- 表类型将始终是 InnoDB
- 那不是NULL 列将始终保持原样 问题
:您认为第一种方法有什么令人反感的地方吗?
I have a situation in which I don't want inserts to take place (the transaction should rollback) if a certain condition is met. I could write this logic in the application code, but say for some reason, it has to be written in MySQL itself (say clients written in different languages will be inserting into this MySQL InnoDB table) [that's a separate discussion].
Table definition:
CREATE TABLE table1(x int NOT NULL);
The trigger looks something like this:
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
NEW.x = NULL;
END IF;
END;
I am guessing it could also be written as(untested):
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
ROLLBACK;
END IF;
END;
But, this doesn't work:
CREATE TRIGGER t1 BEFORE INSERT ON table1 ROLLBACK;
You are guaranteed that:
- Your DB will always be MySQL
- Table type will always be InnoDB
- That NOT NULL column will always stay the way it is
Question: Do you see anything objectionable in the 1st method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自触发文档:
无法创建您的第二个选项。然而:
因此,Eric 建议使用保证会导致错误的查询,这是下一个选择。然而,MySQL 没有能力引发自定义错误——您将需要处理误报。由于缺乏自定义错误处理,封装在存储过程中不会更好...
如果我们了解有关您的条件的更多详细信息,则可能可以通过约束来处理它。
更新
我已经确认,虽然 MySQL 有 CHECK 约束语法,但它不是由任何引擎强制执行的。如果锁定对表的访问,则可以在存储过程中处理限制逻辑。以下触发器不起作用,因为它正在引用要插入的表:
..导致 MySQL 错误 1235。
From the trigger documentation:
Your second option couldn't be created. However:
So Eric's suggestion to use a query that is guaranteed to result in an error is the next option. However, MySQL doesn't have the ability to raise custom errors -- you'll have false positives to deal with. Encapsulating inside a stored procedure won't be any better, due to the lack of custom error handling...
If we knew more detail about what your condition is, it's possible it could be dealt with via a constraint.
Update
I've confirmed that though MySQL has CHECK constraint syntax, it's not enforced by any engine. If you lock down access to a table, you could handle limitation logic in a stored procedure. The following trigger won't work, because it is referencing the table being inserted to:
..results in MySQL error 1235.
您是否尝试过引发错误以强制回滚?例如:
Have you tried raising an error to force a rollback? For example: