根据我的经验,它们不是一个好主意,因为它们可能会导致令人惊讶的副作用,并且很难调试(特别是当一个触发器触发另一个触发器时)。通常情况下,开发人员甚至不会考虑是否存在触发因素。
另一方面,如果每次在数据库中创建新FOO时都必须执行逻辑,那么将其放在FOO表上的插入触发器可能是最安全的地方。
我们唯一使用触发器的时候是非常简单的事情,比如设置一行的修改日期字段。
我正在努力弄清楚触发器是否有必要,并感谢任何建议。如果它们是必要的,在实施它们时要考虑的最重要的问题是什么?
根据我的经验,它们不是一个好主意,因为它们可能会导致令人惊讶的副作用,并且很难调试(特别是当一个触发器触发另一个触发器时)。通常情况下,开发人员甚至不会考虑是否存在触发因素。
另一方面,如果每次在数据库中创建新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...
所以,如果你正确地看待你所做的事情,它们是很棒的。如果是一些非常简单的事情,如审核、总结、自动排序等,那就没问题。只需要记住表的增长速度以及触发器将如何影响性能。
其他回答
事实上,触发器经常被滥用。事实上,在大多数情况下,你甚至不需要它们。但这并不意味着它们就一定是坏事。
我想到的一个触发器很有用的场景是,当你有一个遗留应用程序,你没有源代码,也没有办法改变它。
大多数情况下,是的。
扳机的困难在于它是“在你背后”做事情的;维护应用程序的开发人员很容易没有意识到它的存在,甚至在没有注意到的情况下做了一些更改,把事情搞砸了。
它增加了一层复杂性,增加了维护工作。
不使用触发器,存储过程/例程通常可以做同样的事情,但以一种清晰和可维护的方式-调用存储例程意味着开发人员可以查看其源代码并确切地了解发生了什么。
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.
触发器的概念并不邪恶,限制触发器的嵌套是邪恶的。
说他们是邪恶的是一种夸张,但他们可以引起网格。当一个触发器触发其他触发器时,情况就变得非常复杂了。让我们假设它们很麻烦:http://www.oracle.com/technology/oramag/oracle/08-sep/o58asktom.html
由于多并发问题,在Oracle中使用触发器执行业务逻辑比看起来要难。在其他会话提交之前,您不会在另一个会话中看到更改。