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

另一方面,如果每次在数据库中创建新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.

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

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

触发器的主要问题是

它们是完全全局的——无论表活动的上下文是什么,它们都适用; 他们是隐秘的;你很容易忘记他们的存在,直到他们用意想不到的(非常神秘的)后果伤害了你。

这只是意味着它们需要在适当的情况下谨慎使用;在我的经验中,这仅限于关系完整性问题(有时比您可以声明的粒度更细);而且通常不是出于商业或交易目的。YMMV。

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

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