根据我的经验,它们不是一个好主意,因为它们可能会导致令人惊讶的副作用,并且很难调试(特别是当一个触发器触发另一个触发器时)。通常情况下,开发人员甚至不会考虑是否存在触发因素。

另一方面,如果每次在数据库中创建新FOO时都必须执行逻辑,那么将其放在FOO表上的插入触发器可能是最安全的地方。

我们唯一使用触发器的时候是非常简单的事情,比如设置一行的修改日期字段。

我正在努力弄清楚触发器是否有必要,并感谢任何建议。如果它们是必要的,在实施它们时要考虑的最重要的问题是什么?


当前回答

在高层次上,触发器有两个用例1

1)让事情“自动地”发生。在这种情况下,触发器会产生副作用,它们会以超出预期的方式改变数据,因为执行了(原语)操作符insert、update或delete并导致触发器触发。

这里的普遍共识是,触发器确实有害。因为它们改变了INSERT、UPDATE或DELETE语句的众所周知的语义。更改这三个原语SQL操作符的语义将会对其他开发人员造成不利影响,这些开发人员将来需要对数据库表进行操作,而这些表在使用SQL原语操作时不再以预期的方式运行。

2)执行数据完整性规则,而不是我们可以声明式处理的规则(使用CHECK, PRIMARY KEY, UNIQUE KEY和外键)。在这个用例中,所有触发器所做的就是查询(SELECT)数据,以验证由INSERT/UPDATE/DELETE所做的更改是否被允许。就像声明性约束对我们的作用一样。只有在这种情况下,我们(开发人员)才编写了实施程序。

对于后一种用例,使用触发器是无害的。

我的博客地址是:http://harmfultriggers.blogspot.com

其他回答

触发器的概念并不邪恶,限制触发器的嵌套是邪恶的。

不是邪恶的。它们实际上简化了事情

1.记录/审计对记录甚至数据库模式的更改

您可以在ALTER TABLE上设置一个触发器,用于回滚生产环境中的更改。这应该可以防止任何意外的表修改。


2.跨多个数据库强制执行引用完整性(主键/外键关系等)

I think triggers are not only not evil, but necessary to good database design. Application programmers think that databases are only affected by their application. They are often wrong. If data integrity is to be maintained no matter where the data change came from, triggers are a requirement and it is foolish to avoid them because some programmers are too ethnocentric to consider that something other than their prized application may be affecting things. It isn't hard to design or test or troubleshoot a trigger if you are a competent database developer. Nor it is difficult to determine that a trigger is causing an unexpected result if it occurs to you (as it does to me) to look there. If I get an error saying a table that I'm not referencing in my sp has an FK error, I know without even thinking about it that trigger is causing the problem and so should any competent database developer. Putting business rules only in the application is the number one cause I have found of bad data as others have no idea that rule even exists and violate it in their processes. Data-centric rules belong in the database and triggers are key to enforcing the more complex ones.

他们绝对不是邪恶的。我发现在重构数据库模式、重命名列或将列分成两列或相反(例如:姓名/姓氏情况)并协助转换时,触发器非常宝贵。

它们对于审计也非常有用。

事实上,触发器经常被滥用。事实上,在大多数情况下,你甚至不需要它们。但这并不意味着它们就一定是坏事。

我想到的一个触发器很有用的场景是,当你有一个遗留应用程序,你没有源代码,也没有办法改变它。