Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reasons for objection to SQL triggers that insert data into other tables?

I'm being told by a person with some authority in our company that it's a "database no-no" to create triggers in a database that change rows in another table.

I've used this technique to create default initial configuration, auto-maintaining audit logs, and various other things that would have been a nightmare to consistently maintain inside the heterogeneous applications that connect to that database. For over a decade, I've read that this as an appropriate way to centralize relationship constraint maintenance and get the responsibility out of the applications interacting with the data.

As such, my BS meter is pegging with this. Am I missing something fundamentally wrong with that technique that makes it a bad practice in general?

like image 640
Alan Krueger Avatar asked Jul 22 '11 16:07

Alan Krueger


People also ask

Why we should not use triggers in SQL?

Triggers are generally over-used in SQL Server. They are only rarely necessary, can cause performance issues, and are tricky to maintain If you use them, it is best to keep them simple, and have only one operation per trigger.

Why does this trigger fails when inserting a row into player table?

The trigger fails because it needs to be a row level AFTER UPDATE trigger. The trigger fails because a SELECT statement on the table being updated is not allowed. The trigger fails because you cannot use the minimum and maximum functions in a BEFORE UPDATE trigger.

What Cannot have a trigger associated with it new table?

A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. The trigger becomes associated with the table named tbl_name , which must refer to a permanent table. You cannot associate a trigger with a TEMPORARY table or a view.

Which of the following Cannot be a triggering event for a trigger?

Explanation: Triggers are not possible for create, drop.


1 Answers

If you are careful with your trigger code, there is nothing inherently bad about it. Some people get bitten by bad trigger code and then decide that triggers are bad (eventhough it was the bad trigger code that was the problem). They then generalize this as, "never use triggers".

The other problem is....

Using the audit tables as an example, suppose you have a stored procedure that updates a table AND puts data in to an audit table. Now suppose you write trigger code to put data in to the audit table. You could end up with duplicate audit data.

like image 56
George Mastros Avatar answered Oct 13 '22 19:10

George Mastros