SQL Server Forum / Programming / SQL / July 2008
Why is use of triggers discouraged?
|
|
Thread rating:  |
Omid Golban - 18 Jul 2008 07:36 GMT I have been working with SQL server for only 6 months and am surprised to notice most articles discourage use of triggers. What is the reason?
Thank you, Omid
vinu - 18 Jul 2008 08:39 GMT Omid
see the link http://blog.sqlauthority.com/2007/05/24/sql-server-disadvantages-problems-of-tri ggers/
vinu
>I have been working with SQL server for only 6 months and am surprised to > notice most articles discourage use of triggers. What is the reason? > > Thank you, > Omid Erland Sommarskog - 18 Jul 2008 10:00 GMT > I have been working with SQL server for only 6 months and am surprised to > notice most articles discourage use of triggers. What is the reason? There are two basic things you can use triggers for: 1) Enforce business rules, and rollback in case of errors. 2) Perform cascading updates. (Which includes auditing, signaling to other systems.)
The major problems with triggers is that if someone accidently drops a trigger, there will not be any error, but the system will job along happily. On the other hand, if someone deletes a stored procedure, error messages will appear all over the place.
If the dropped trigger only perform checking actions the damage is limited, as long as the application performs its job. But if the trigger was supposed to perform updates, we now have a database that is corrupt on application level.
So seen from this point of view, it's better to put the cascading updates in the stored procedures. However, this assumes that the application always calls the stored procedure. And more importantly, it assumes that no one goes and updates the table directly through an SQL window. Which, after all, is more likely than the trigger being dropped. On the other hand a direct SQL update may concern a single row only, so the damage is limited.
Another issue with triggers is that if you overdo it, you may get entangled in very complex logic. Triggers tend do be a bit more difficult to program than stored procedures.
In the end, it's a trade-off. Do it in the trigger or in the stored procedure? What is the damage if the trigger is dropped? How complex are the updates? And so on. But to say "never use triggers" is a bad idea, in my opinion.
In the system I work with, we have actually taken precautions, so we know which triggers should be there, and the application does not start if a trigger is missing.
 Signature Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Books Online for SQL Server 2005 at http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx Books Online for SQL Server 2000 at http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
steve dassin - 18 Jul 2008 10:32 GMT I'll give you some reasons and none of them have anything to do with normalization or performance.
http://beyondsql.blogspot.com/2008/07/demoralization-by-trigger.html http://beyondsql.blogspot.com/2007/10/sql-undefined-trigger.html
www.beyondsql.blogspot.com
Alex Kuznetsov - 18 Jul 2008 14:22 GMT On Jul 18, 1:36 am, Omid Golban <OmidGol...@discussions.microsoft.com> wrote:
> I have been working with SQL server for only 6 months and am surprised to > notice most articles discourage use of triggers. What is the reason? > > Thank you, > Omid not completely reliable. My canned answers:
http://www.devx.com/dbzone/Article/31985 http://www.devx.com/dbzone/Article/34479/0 http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/05/13/be-aware-of-thes e-loopholes-in-your-referential-integrity.aspx
steve dassin - 19 Jul 2008 02:19 GMT > On Jul 18, 1:36 am, Omid Golban <OmidGol...@discussions.microsoft.com> > wrote: [quoted text clipped - 9 lines] > http://www.devx.com/dbzone/Article/34479/0 > http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/05/13/be-aware-of-thes e-loopholes-in-your-referential-integrity.aspx Allow me to rephrase, "My Can of the Trigger" :) Their implememtation is seriously flawed.
On a more serious note, I would like to bring to your attention the following article:
'Spending Moore's Dividend' by James Larus, Microsoft Research ftp://ftp.research.microsoft.com/pub/tr/TR-2008-69.pdf
The is an important, powerful and even stinging look over the last 30 years of what software vendors have done with hardware advances. He uses a broad brush to paint a very interesting picture. I should think someone like yourself, having a background with dbms and object oriented frameworks, would find this a very intriguing and thought provoking read. (Is this guy friendly with current development teams?:)
For a bit more insight into where his head is see: 'Operating Systems Should Control the Execution Environment' http://research.ihost.com/vee/vee06/larus.html (additional links available in above.)
Remarkably, I can find next to nothing in response to this article on the net. I hope you get a chance to read him and perhaps think of how you could make at least his ideas on what has happened in the past relevant to sql server users:)
steve
steve dassin - 19 Jul 2008 02:22 GMT > On Jul 18, 1:36 am, Omid Golban <OmidGol...@discussions.microsoft.com> > wrote: [quoted text clipped - 9 lines] > http://www.devx.com/dbzone/Article/34479/0 > http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/05/13/be-aware-of-thes e-loopholes-in-your-referential-integrity.aspx Allow me to rephrase, "My Can of the Trigger" :) Their implememtation is seriously flawed.
On a more serious note, I would like to bring to your attention the following article:
'Spending Moore's Dividend' by James Larus, Microsoft Research ftp://ftp.research.microsoft.com/pub/tr/TR-2008-69.pdf
The is an important, powerful and even stinging look over the last 30 years of what software vendors have done with hardware dvances. He uses a broad brush to paint a very interesting picture. I should think someone like yourself, having a background with dbms and object oriented frameworks, would find this a very intriguing and thought provoking read. (Is this guy friendly with current development teams?:)
For a bit more insight into where his head is see: 'Operating Systems Should Control the Execution Environment' http://research.ihost.com/vee/vee06/larus.html (additional links available in above.)
Remarkably, I can find next to nothing in response to this article on the net. I hope you get a chance to read him and perhaps think of how you could make at least his ideas on what has happened relevant to sql server users:)
steve
Alex Kuznetsov - 20 Jul 2008 04:31 GMT > > On Jul 18, 1:36 am, Omid Golban <OmidGol...@discussions.microsoft.com> > > wrote: [quoted text clipped - 18 lines] > 'Spending Moore's Dividend' > by James Larus, Microsoft Researchftp://ftp.research.microsoft.com/pub/tr/TR-2008-69.pdf While this is definitely a very interesting read, thank you for the link, the following statement does not make sense:
"Linux exhibits much the same pattern of growth (Figure 8)."
The author compares exponential growth in Fig 7, which only looks linear because the author uses logarithmic scale on the vertical axis, and alleges that a genuine linear growth in Fig 8 is "much the same pattern"? Anybody with basic math skills can see that this is simply not true ;)
steve dassin - 21 Jul 2008 02:45 GMT >> > On Jul 18, 1:36 am, Omid Golban <OmidGol...@discussions.microsoft.com> >> > wrote: [quoted text clipped - 31 lines] > pattern"? Anybody with basic math skills can see that this is simply > not true ;) Do you really want to throw the baby out with the bathwater because of it? I'm suggesting the author is making a bold statement and no one's listening:) But then again is anyone listening when I try to show the 'model' sql is using is highly questionable? Do you see where I'm going with this :)
Roy Harvey (SQL Server MVP) - 21 Jul 2008 13:54 GMT >m suggesting the author is making a bold statement and no one's >listening:) I found the article interesting, but I didn't see any really new insights. It was nice to see someone try to quantify what amounts to common sense, but I didn't see anything to get all excited about.
While I love the idea of every machine having multiple CPUs, I find the idea of them just being more of the same type of CPU as we have been using all along discouraging. I don't believe that is the path to effective massively parallel computing. That will require a fundamentally new architecture. If the author has any thoughts along those lines I missed them.
Roy Harvey Beacon Falls, CT
Alex Kuznetsov - 21 Jul 2008 15:47 GMT > > While this is definitely a very interesting read, thank you for the > > link, the following statement does not make sense: [quoted text clipped - 8 lines] > > Do you really want to throw the baby out with the bathwater because of it? The author made a very fundamental mistake in basic math. I read it anyway, like a sci-fi story.
Roy Harvey (SQL Server MVP) - 21 Jul 2008 16:13 GMT >The author made a very fundamental mistake in basic math. I read it >anyway, like a sci-fi story. I think the LINUX stuff was added as an afterthought. The other LINUX graph was also not logarithmic, and those two were the only ones that were not.
I also found a problem in the first paragraph, where a period starting in 1985 and ending with the introduction of Core 2 Duo was specified as ten years.
Roy Harvey Beacon Falls, CT
steve dassin - 22 Jul 2008 02:42 GMT >. >The author made a very fundamental mistake in basic math. I read it >anyway, like a sci-fi story. You really like all the APIs todays? You really think memory allocation, garbage collection and virtual memory make up the best architecture to take advantage of hardware advances? Doesn't all the bloat get your goat?:)
Alex Kuznetsov - 22 Jul 2008 21:13 GMT > >. > >The author made a very fundamental mistake in basic math. I read it [quoted text clipped - 3 lines] > garbage collection and virtual memory make up the best architecture to take > advantage of hardware advances? Doesn't all the bloat get your goat?:) Regardless of my feelings towards GC, I really feel that I can run any latest flavor of Linux on the old box I was using a decade ago. In the universe I live and work in, apparently Linux does not manifest the trends similar to Windows' trends. Of course I might be wrong, I did not actually try to run Ubuntu on that old box, I threw it away instead.
Eric Russell - 18 Jul 2008 15:04 GMT The problem with triggers is that they are often times overused. Because it is fired every time a table is modified, a complex trigger can become a performance or concurrency bottleneck. Also, developers often use triggers for operations that would best be implemented using a stored procedure, check constraints, or a scheduled job. For example, if your application or stored procedure updates the [DBAmount] column, then don't leave it up to a trigger to update the associated [CRAmount] column.
That said, there are a few situations where triggers are a natural solution.
Referential integrity constraints can only be applied to tables within the same database, so triggers can be used to implement cross database referential integrity. For example, the column [Sales].OrderDetail.SKU column should only contain a value contained in the column [Product].Products.SKU.
Another use for triggers is insert / update / delete auditing. For example: ... insert into History.dbo.Customer (ModDate, ModType, CustomerID, CustomerName, ...) select getutcdate(), 'I', CustomerID, CustomerName, ... from INSERTED ...
> I have been working with SQL server for only 6 months and am surprised to > notice most articles discourage use of triggers. What is the reason? > > Thank you, > Omid Stuart Ainsworth - 19 Jul 2008 13:48 GMT On Jul 18, 2:36 am, Omid Golban <OmidGol...@discussions.microsoft.com> wrote:
> I have been working with SQL server for only 6 months and am surprised to > notice most articles discourage use of triggers. What is the reason? > > Thank you, > Omid I went to a conference once and heard the presenter describe triggers as "voodoo programing: you could do an insert against a table and the lights would go off in the building next door." I think there are lots of technical reasons (see all of the responses above) as to why triggers are discouraged, but I also believe that many SQL programmers are uncomfortable using them because their main purpose is to be invisible. SQL is a very simple language, and it's a bit disconcerting to attempt to do something simple with that language (like an INSERT statement) and have something else altogether happen.
Stu
Gert-Jan Strik - 19 Jul 2008 23:45 GMT Others have mentioned a lot of disadvantages. However, no one will deny that triggers have their place!
I think most of the times they are discouraged when compared to Declared Referential Integrity (DRI). When possible, DRI is the preferred way to specify integrity rules. When using DRI, the declare integrity rule will be guaranteed (try implementing a Foreign Key constraint using a trigger...), have a good and (typically) bugfree implementation, are sometimes structurally faster than the trigger equivalent (such as a Unique constraint). Basically, you would be re-inventing the wheel if a DRI version of your integrity rule is available.
 Signature Gert-Jan SQL Server MVP
> I have been working with SQL server for only 6 months and am surprised to > notice most articles discourage use of triggers. What is the reason? > > Thank you, > Omid --CELKO-- - 20 Jul 2008 14:41 GMT >> .. am surprised to notice most articles discourage use of triggers. What is the reason? << 1) The SQL Server syntax is highly proprietary and will not port. It is also weak version compared to the Standards and other products. 2) The optimizer cannot use procedural code. 3) 90% of all triggers can now be replaced by DRI actions.
There will be a few times when a trigger is needed, but they are usually a symptom of a poor design. You can kludging a design flaw by jumping into procedural code.
Alex Kuznetsov - 20 Jul 2008 15:00 GMT > >> .. am surprised to notice most articles discourage use of triggers. What is the reason? << > 2) The optimizer cannot use procedural code. What do you mean? As a blanket statement, this is simply not true.
Aaron Bertrand [SQL Server MVP] - 20 Jul 2008 16:56 GMT Celko,
I happen to agree with you in general, but I don't favor the arguments you are bringing forward to justify your opinion.
> 1) The SQL Server syntax is highly proprietary and will not port. It > is also weak version compared to the Standards and other products. How is this a problem with triggers, but not with any other type of module? Are all UDFs and stored procedures and constraints 100% portable?
> 2) The optimizer cannot use procedural code. What on earth are you talking about? First of all, do you think the optimizer simply shuts itself off if it sees WHILE or DECLARE CURSOR? And why do you think that all triggers have procedural code?
Aaron
Erland Sommarskog - 20 Jul 2008 20:25 GMT > 3) 90% of all triggers can now be replaced by DRI actions. Given that SQL Server has had DRI for 10 years, one would hope that the trigger RI there once was has been replaced by DRI where this is possible(*). But as you say, there is still 10% that cannot be done with DRI. For instance, checking that you cannot enter an order with a discontinued product.
(*) I will have to confess that I have two tables where the triggers have several checks that could be CHECK constraint. In the first case, it's because I initially did not understand that there was something called table constraint. In the other table, it's mainly a matter of consistency. The trigger performs an awful lot of checks, of which the very most requires looking in other tables, so it seemed logical to keep the few that were intra-table in the trigger as well.
 Signature Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Books Online for SQL Server 2005 at http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx Books Online for SQL Server 2000 at http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
--CELKO-- - 21 Jul 2008 18:59 GMT >> (*) I will have to confess that I have two tables where the triggers have several checks that could be CHECK constraint. << And you are pretty good about maintaining code!
In fairness, in the "old days" before DRI actions, you had to use triggers to cascade actions. But unlike the *= versus LEFT OUTER JOIN syntax, you can port a trigger to the next release, so why bother to change it? Unless someone makes it very easy, the attitude is "if it ain't broke, don't fix it" for most programmers.
Erland Sommarskog - 21 Jul 2008 23:40 GMT > In fairness, in the "old days" before DRI actions, you had to use > triggers to cascade actions. But unlike the *= versus LEFT OUTER JOIN > syntax, you can port a trigger to the next release, so why bother to > change it? Unless someone makes it very easy, the attitude is "if it > ain't broke, don't fix it" for most programmers. We changed all almost our trigger-based RI to DRI when we got 6.0, but part of the plot was that we for several other reasons made a clean break, and kind of started with a blank page, rather than just jogging along with the old system. (We did copy more than one thing from the old system, though.)
There were a few left behind, because there were tables which an RI that said "this FK references this table or that table". Which is simple to do in a trigger, but not fun with DRI, and those tables were fixed later.
 Signature Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Books Online for SQL Server 2005 at http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx Books Online for SQL Server 2000 at http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
steve dassin - 21 Jul 2008 02:30 GMT >>> .. am surprised to notice most articles discourage use of triggers. What >>> is the reason? << [quoted text clipped - 7 lines] > usually a symptom of a poor design. You can kludging a design flaw by > jumping into procedural code. Interesting logic. Because sql offers only rudimentary constructs for constraints, those who attempt to use what is available are guilty of poor design. Just as dynamic sql is a symptom of poor design. You have the right crime but the wrong party. Your reasoning has an intellectual name - Meshuggah.
For a target (constraint) rich environment visit: www.beyondsql.blogspot.com
Uri Dimant - 21 Jul 2008 07:56 GMT Steve
>Your reasoning has an intellectual name - Meshuggah. Is it in hebrew?
>>>> .. am surprised to notice most articles discourage use of triggers. >>>> What is the reason? << [quoted text clipped - 16 lines] > For a target (constraint) rich environment visit: > www.beyondsql.blogspot.com steve dassin - 21 Jul 2008 10:47 GMT Hi Uri,
Of course, and I meant 'meshugas'!:) Damn, how did I screw that up?:( :) Thanks for pointing me in the right direction:)
> Steve >>Your reasoning has an intellectual name - Meshuggah. [quoted text clipped - 21 lines] >> For a target (constraint) rich environment visit: >> www.beyondsql.blogspot.com Uri Dimant - 21 Jul 2008 11:58 GMT Well, I can think that this word to be in wide use in your surroundings:-))) That means you probably know another word 'hutzpa':-))))))
> Hi Uri, > [quoted text clipped - 26 lines] >>> For a target (constraint) rich environment visit: >>> www.beyondsql.blogspot.com steve dassin - 21 Jul 2008 13:19 GMT > Well, I can think that this word to be in wide use in your > surroundings:-))) That means you probably know another word > 'hutzpa':-)))))) Yeah, I think there's way too much of the former and not enough of the latter these days! :) I do appreciate both and I love the words themselves :)
steve dassin - 22 Jul 2008 02:19 GMT > Well, I can think that this word to be in wide use in your > surroundings:-))) Ah, now that I read this again I see what you're driving at. This is your gentle way of saying it is I who am meshugas! :-) Well let me put it this way, what appears to you as meshigas today may appear as only common sense tomorrow. It is possible that you will have a very pleasant epiphany and get 'it'. I can't think of a nicer person that I could wish this on :))
>That means you probably know another word 'hutzpa':-)))))) Can you think of a better description of those who try to bring about change? In general there is way too little hutzpa around here:) What is the opposite of hutzpa? :)
Uri Dimant - 22 Jul 2008 06:44 GMT Steve
God forbid, that was my intend to offence you. I like read your posts
Well let me put it this
> way, what appears to you as meshigas today may appear as only common sense > tomorrow. Agree for 100 percent
What is the
> opposite of hutzpa? :) In hebrew we say 'menumas'
>> Well, I can think that this word to be in wide use in your >> surroundings:-))) [quoted text clipped - 10 lines] > change? In general there is way too little hutzpa around here:) What is > the opposite of hutzpa? :) Uri Dimant - 22 Jul 2008 07:44 GMT Sorry again Steve, I meant God forbid, that was NOT intend to offence you
> Steve > [quoted text clipped - 26 lines] >> change? In general there is way too little hutzpa around here:) What is >> the opposite of hutzpa? :) steve dassin - 22 Jul 2008 09:52 GMT > Sorry again Steve, I meant > God forbid, that was NOT intend to offence you Not to worry, I understand:) You can be playful with me. I appreciate it!:) Playful, a little meshugas, is a good thing:)
best, steve
steve dassin - 22 Jul 2008 09:47 GMT > Steve > > God forbid, that was my intend to offence you.
:):)
|
|
|