Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create or alter trigger if exists

I'm trying to determine withing if If I should create or alter and trigger. My Code is below.

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?

like image 910
szpic Avatar asked Aug 11 '15 11:08

szpic


People also ask

How do you modify an existing trigger?

To modify a DML trigger In Object Explorer, connect to an instance of Database Engine and then expand that instance. Expand the database that you want, expand Tables, and then expand the table that contains the trigger that you want to modify. Expand Triggers, right-click the trigger to modify, and then click Modify.

How do you check if a trigger exists or not?

We can use the sys. triggers catalog view to check the existence of a Database scoped triggers. DML triggers are Database scoped triggers, where as DDL triggers can be DATABASE scoped or SERVER scoped.

How do you check if trigger already exists in SQL Server?

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.


2 Answers

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);
like image 156
Gordon Linoff Avatar answered Sep 22 '22 18:09

Gordon Linoff


Using this articular as my source of truth. here is the short answer.

As of SQL Server 2016 sp1 you can use create or alter statements instead of other drop and create methods (my personal fav till this) on some of the database objects (stored procedures/functions/triggers/views).

so your script could look like

create or alter TRIGGER Sales.bonus_reminder
    ON Sales.SalesPersonQuotaHistory
    WITH ENCRYPTION
    AFTER INSERT, UPDATE 
    AS RAISERROR ('Notify Compensation', 16, 10)
like image 30
workabyte Avatar answered Sep 25 '22 18:09

workabyte