Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I list (or export) the code for all triggers in a database?

I'm changing from local time to UTC-time in our database.
There are alot of triggers that copies information to history tables that currently uses GETDATE().

I would like to find every trigger that uses GETDATE() (instead of GETUTCDATE()) in the database, is there any way to do this automatic?

I've listed them by select * from sys.triggers but I also need to see the actual code to be able to find the use of GETDATE().

like image 313
nj. Avatar asked Jun 28 '11 14:06

nj.


People also ask

How can I see all triggers in database?

To view database level triggers, Login to the server using SQL Server management studio and navigate to the database. Expand the database and navigate to Programmability -> Database Triggers. To view triggers at the server level, Login to Server using SSMS and navigate to Server Objects and then Triggers folder.

Which command returns list of triggers?

SHOW TRIGGERS lists the triggers currently defined for tables in a database (the default database unless a FROM clause is given). This statement returns results only for databases and tables for which you have the TRIGGER privilege.

Can you list down types of triggers?

Types of SQL TriggersDML (data manipulation language) triggers – We've already mentioned them, and they react to DML commands. These are – INSERT, UPDATE, and DELETE. DDL (data definition language) triggers – As expected, triggers of this type shall react to DDL commands like – CREATE, ALTER, and DROP.


2 Answers

Your could try the following:

SELECT      o.[name],
            c.[text]
FROM        sys.objects AS o
INNER JOIN  sys.syscomments AS c
ON      o.object_id = c.id
WHERE   o.[type] = 'TR'
like image 72
Maximilian Mayerl Avatar answered Sep 17 '22 14:09

Maximilian Mayerl


Here's the script I used to export triggers:

DECLARE @t VARCHAR (MAX)
SET @t = ''
SELECT @t = @t + 'IF EXISTS (SELECT 1 FROM sys.triggers WHERE object_id = OBJECT_ID(N''' + s.name + '.' + o.name +'''))
DROP TRIGGER ' + s.name + '.' + o.name + '
GO
' + OBJECT_DEFINITION (OBJECT_ID( s.name + '.' + o.name )) +'
GO
'
FROM sys.objects o
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
INNER JOIN sys.objects o2 ON o.parent_object_id = o2.object_id
WHERE o. [type] = 'TR'
AND (
OBJECTPROPERTY ( o.object_id , 'ExecIsInsertTrigger' ) = 1
OR
OBJECTPROPERTY ( o.object_id , 'ExecIsUpdateTrigger' ) = 1
OR
OBJECTPROPERTY ( o.object_id , 'ExecIsDeleteTrigger' ) = 1
)
SELECT @t AS [processing-instruction(x)] FOR XML PATH ('')

More details here if it doesn't make sense to anyone:

http://paulfentonsql.co.uk/2015/09/01/generate-createdrop-statements-for-all-triggers-of-a-given-type/

like image 40
Paul Fenton Avatar answered Sep 21 '22 14:09

Paul Fenton