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

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

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

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


当前回答

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.

其他回答

触发器有它们的用途——日志记录/审计和维护“最后修改”日期是两个非常好的用途,在之前的回复中已经提到过。

然而,优秀设计的核心原则之一是业务规则/业务逻辑/无论你想称呼它什么,都应该集中在一个地方。将一些逻辑放在数据库中(通过触发器或存储过程),将一些逻辑放在应用程序中违反了这一原则。在两个地方复制逻辑更糟糕,因为它们总是会彼此不同步。

还有一个已经提到过的“最小意外原则”问题。

我知道有些开发人员认为触发器应该总是用于实现他们想要的功能的最直接方式,而有些开发人员则永远不会这样做。这几乎就像是两个阵营之间的教条。

然而,我个人完全同意MarkR -你可以(几乎)总是编写与触发器功能相当的代码,这将更清晰,因此更容易维护。

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

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

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

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

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


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

如果有副作用,那就是故意造成的问题。 在一些数据库系统中,没有其他方法可以设置一个自增字段,即主键ID字段。