Scenario:
Each time data is inserted/updated/deleted into/in/from a table, up to 3 things need to happen:
- The data needs to be logged to a separate table
- Referencial integrity must be enforced on implicit related data (I’m referring to data that should be linked with a foreign key relationship, but isn’t: eg. When a updating
Table1.Nameshould also updateTable2.Nameto the same value) - Arbitrary business logic needs to execute
The architecture and schema of the database must not be changed and the requirements must be accomplished by using triggers.
Question
Which option is better?:
- A single trigger per operation (insert/update/delete) that handles multiple concerns (logs, enforces implicit referencial integrity, and executes arbitrary business logic). This trigger could be named
D_TableName(“D” for delete). -
Multiple triggers per operation that were segregated by concern. They could be named:
D_TableName_Logging– for logging when something is deleted fromD_TableName_RID_TableName_BL
I prefer option 2 because a single unit of code has a single concern. I am not a DBA, and know enough about SQL Server to make me dangerous.
Are there any compelling reasons to handle all of the concerns in a single trigger?
Wow, you are in a no-win situation. Who ever requested that all this stuff be done via triggers should be shot and then fired. Enforcing RI via triggers?
You said the architecture and schema of the database must not be changed. However, by creating triggers, you are, at the very least, changing the schema of the database, and, it could be argued, the architecture.
I would probably go with option #1 and create additional stored procs and UDFs that take care of logging, BL and RI so that code is not duplicated amoung the individual triggers (the triggers would call these stored procs and/or UDFs). I really don’t like naming the triggers they way you proposed in option 2.
BTW, please tell someone at your organization that this is insane. RI should not be enforced via triggers and business logic DOES NOT belong in the database.