First Post in this series: SQL Advent Calendar 2013-Day 1- Placeholders in SQL Prompt Snippets
As I was hanging our family Advent Calendar up, I thought I would make one for you, my readers. I’ll be sharing my scripts from two of my favorite products as well as tips on how to create your own.
Oh where, oh where did my trigger go?
On Day 8, Day 9, and Day 10 I wrote about using 4 Change tracking fields in tables. Two of the fields, ModifiedBy and ModifiedDTS are updated in a trigger. If you are slowly making changes to many tables, you can loose track of which tables have the triggers you need.
This little snippet for SQL Prompt, called FindTrig, will get two result sets for you. The first result set is a comma delimited list of tables that have the ModifiedDTS field, but do not have a trigger with the pattern trg__u. The second result set will show you a the same list of tables and the triggers they already have. This will be helpful when the code to update ModifiedBy and ModifiedDTS was added to a different trigger than expected. You definitely don’t want two triggers updating the same two fields. That will cause an infinite loop of updates.
USE <DBName,string, $DBNAME$> GO /* *********************************************************************************** Purpose: Creates a comma delimited list of tables that may need a trigger to populate the ModifiedBy and ModifiedDTS fields Author: mstuewe Date: 12/17/2013 ************************************************************************************ */ DECLARE @Tables AS nvarchar(max) SELECT @Tables = ISNULL(@Tables + ',', '') + t.name FROM sys.objects AS t JOIN sys.all_columns AS c ON c.object_id = t.object_id LEFT JOIN sys.Triggers AS Tr ON tr.name = 'trg_' + t.name + '_iu' OR tr.name = 'trg_' + t.name + '_u' WHERE t.type = 'U' AND c.NAME = 'ModifiedDTS' AND tr.name IS NULL ORDER BY t.name IF @Tables IS NULL PRINT 'All tables have a trigger.' ELSE BEGIN SELECT @Tables AS TableNames SELECT t.NAME AS TableName ,tr.name AS ExistingTrigger FROM ( SELECT t.object_id ,t.name FROM sys.objects AS t JOIN sys.all_columns AS c ON c.object_id = t.object_id LEFT JOIN sys.Triggers AS Tr ON tr.name = 'trg_' + t.name + '_iu' OR tr.name = 'trg_' + t.name + '_u' WHERE t.type = 'U' AND c.NAME = 'ModifiedDTS' AND tr.name IS NULL ) AS t LEFT JOIN sys.Triggers AS Tr ON Tr.parent_id = t.object_id ORDER BY t.name END GO
As an example, I created three tables with the four changing tracking fields, Employee, Phone, and PhoneType. I added the trigger to Employee and Phone, but the trigger for Phone had it’s name change. After looking at the results returned, I would know that I only need to create a trigger script for the PhoneType table.
Note: You can download this snippet from my Script Library under Resources. It’s called FindTrig. |
Previous Post In Series: SQL Advent Calendar – Day 16 – Snippet For In-Line Table Functions