I’m trying to determine withing if If I should create or alter and trigger. My Code is below.
x
IF OBJECT_ID(N'Sales.bonus_reminder', N'TR') IS NOT NULL
ALTER TRIGGER Sales.bonus_reminder
ON Sales.SalesPersonQuotaHistory
AFTER INSERT
AS RAISERROR ('Notify Compensation', 16, 10);
else
CREATE TRIGGER Sales.bonus_reminder
ON Sales.SalesPersonQuotaHistory
WITH ENCRYPTION
AFTER INSERT, UPDATE
AS RAISERROR ('Notify Compensation', 16, 10);
The errors I’m getting are :
- Incorrect syntax near else
- Create trigger should be the only statement in batch.
How this code should look like?
Advertisement
Answer
If you don’t want to the create trigger statement as dynamic SQL, then you can do something like this:
IF OBJECT_ID(N'Sales.bonus_reminder', N'TR') IS NOT NULL
exec sp_executesql N'DROP TRIGGER Sales.bonus_reminder';
GO
CREATE TRIGGER Sales.bonus_reminder
ON Sales.SalesPersonQuotaHistory
WITH ENCRYPTION
AFTER INSERT, UPDATE
AS RAISERROR ('Notify Compensation', 16, 10);