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

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

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

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


当前回答

如果使用得当,触发器是一个很好的工具。特别是对于审计变更、填充汇总表等。

Now they can be "evil" if you end up in "trigger hell" with one trigger that kicks off other triggers. I once worked on a COTS product where they had what they called "flex triggers." These triggers were stored in a table as dynamic sql stings are were compiled every time they were executed. Compiled triggers would do a look up and see if that table had any flex triggers to run and then compile and run the "flex" trigger. In theory this sounded like a really cool idea because the product was easily customized but the reality was the database pretty much exploded due to all the compiles it had to do...

所以,如果你正确地看待你所做的事情,它们是很棒的。如果是一些非常简单的事情,如审核、总结、自动排序等,那就没问题。只需要记住表的增长速度以及触发器将如何影响性能。

其他回答

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

不,其实这是个好主意。如果你的特定触发器有问题,那么你做得不对,但这通常意味着你的实现有问题,而不是触发器本身的概念:-)。

我们经常使用触发器,因为它将特定于dbms的活动置于其所属数据库的控制之下。DBMS的用户不应该担心这类事情。数据的完整性取决于数据库本身,而不是使用它的应用程序或用户。如果数据库中没有约束、触发器和其他特性,执行规则的任务就留给了应用程序,只需要一个流氓或有bug的应用程序/用户就可以破坏数据。

例如,如果没有触发器,像自动生成列这样奇妙的东西就不存在了,在选择它们时,您必须在每行上处理一个函数。这可能会降低DBMS的性能,在插入/更新时创建自动生成的列要好得多,因为只有在插入/更新时才会更改列。

此外,缺乏触发器将阻止在DBMS中强制执行数据规则,例如预先触发器,以确保列具有特定的格式。注意,这与数据完整性规则不同,后者通常只是外键查找。

不,他们不邪恶——他们只是被误解了:- d

触发器有一个有效的用途,但往往是作为一个复古黑客,最终使事情变得更糟。

如果您将DB作为应用程序的一部分进行开发,那么逻辑应该始终存在于进行调用的代码或scprocs中。触发器只会导致稍后的调试痛苦。

如果您了解锁、死锁以及DB如何访问磁盘上的文件,那么以正确的方式使用触发器(例如审计或归档直接DB访问)将非常有价值。

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。