How to add "IF NOT EXISTS" to create trigger statement How to add "IF NOT EXISTS" to create trigger statement sql-server sql-server

How to add "IF NOT EXISTS" to create trigger statement


IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRIGGERNAME]'))DROP TRIGGER [dbo].[TRIGGERNAME]goIF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TABLENAME]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)BEGINCREATE   TRIGGER [dbo].[TRIGGERNAME] ON [dbo].[TABLENAME] FOR INSERT, UPDATE AS ...END

Based on your updated question... try this:

IF NOT EXISTS (select * from sys.objects where type = 'TR' and name = 'Insert_WithdrawalCodes')EXEC dbo.sp_executesql @statement = N'CREATE TRIGGER [dbo].[Insert_WithdrawalCodes]    ON  [dbo].[PupilWithdrawalReason]    AFTER INSERTAS BEGIN    SET NOCOUNT ON;        UPDATE [dbo].[PupilWithdrawalReason] SET DateCreated=dbo.SYSTEMTIME()         WHERE WithdrawalCodeID IN (SELECT WithdrawalCodeID FROM inserted)END '


The best way is to check for objects and drop them if they exist before you create them.

Rather then not creating it at all if it exists, I would approach it the other way, drop it if exists and then create.

Normally in long lenghty scripts if you want to update the definition of a trigger you would just simply add this at the end of that script and your trigger definition will be updated.

So the approach should be create the object but drop it if it already exists rather then dont create it at all if it already exists

IF OBJECT_ID ('[Insert_WithdrawalCodes] ', 'TR') IS NOT NULL   DROP TRIGGER [Insert_WithdrawalCodes];GOCREATE TRIGGER .......


Certain statements like CREATE TRIGGER needs to be the first in a batch (as in, group of statements separated by GO ).

https://msdn.microsoft.com/en-us/library/ms175502.aspx

Alternatively you could do this

IF NOT EXISTS ( SELECT  *            FROM    sys.objects            WHERE   type = 'TR'                    AND name = 'Insert_WithdrawalCodes' ) BEGIN    EXEC ('CREATE TRIGGER Insert_WithdrawalCodes ON ...');END;