Cómo agregar "SI NO EXISTE" para crear la instrucción trigger


Estoy usando sql server 2008 R2. Más específicamente, Microsoft SQL Server 2008 R2 (RTM)-10.50.1600.1 (X64) Abr 2 2010 15:48:46 Copyright (c) Microsoft Corporation Standard Edition (64-bit) en Windows NT 6.1 (Build 7601: Service Pack 1) (Hipervisor). Soy nuevo en sql server y procedures / triggers. Tengo el siguiente código para crear un disparador (funciona):

CREATE TRIGGER [dbo].[Insert_WithdrawalCodes] 
   ON  [dbo].[PupilWithdrawalReason] 
   AFTER INSERT
AS 
BEGIN
    SET NOCOUNT ON;
        UPDATE [dbo].[PupilWithdrawalReason] SET DateCreated=dbo.SYSTEMTIME() 
        WHERE WithdrawalCodeID IN (SELECT WithdrawalCodeID FROM inserted)
END

¿Cómo puedo crear condicionalmente solo si el disparador aún no existe? ¿Qué estoy haciendo mal aquí? Stackoverflow tiene buenos ejemplos de "si no existe", pero no puedo hacer que esto funcione junto con un CREATE. Aquí está uno de mis esfuerzos fallidos:

IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'TR' AND name = 'Insert_WithdrawalCodes')
   exec('CREATE TRIGGER [dbo].[Insert_WithdrawalCodes] ON  [dbo].[PupilWithdrawalReason] AFTER INSERT AS BEGIN SET NOCOUNT ON; UPDATE [dbo].[PupilWithdrawalReason] SET DateCreated=dbo.SYSTEMTIME() WHERE WithdrawalCodeID IN (SELECT WithdrawalCodeID FROM inserted) END')
GO
Author: thebiggestlebowski, 2015-01-30

4 answers

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

AS ...

END

Basado en su pregunta actualizada... prueba esto:

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 INSERT
AS 
BEGIN
    SET NOCOUNT ON;
        UPDATE [dbo].[PupilWithdrawalReason] SET DateCreated=dbo.SYSTEMTIME() 
        WHERE WithdrawalCodeID IN (SELECT WithdrawalCodeID FROM inserted)
END


 '
 56
Author: JStevens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-30 15:20:40

La mejor manera es comprobar si hay objetos y soltarlos si existen antes de crearlos.

En lugar de no crearlo en absoluto si existe, lo abordaría de la otra manera, lo soltaría si existe y luego crearía.

Normalmente en scripts largos si desea actualizar la definición de un disparador, simplemente agregue esto al final de ese script y su definición del disparador se actualizará.

Así que el enfoque debe ser create the object but drop it if it already exists en lugar de dont create it at all if it already exists

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

CREATE TRIGGER .......
 9
Author: M.Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-29 22:11:20

Ciertas instrucciones como CREATE TRIGGER deben ser las primeras en un lote (como en un grupo de instrucciones separadas por GO ).

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

Alternativamente puedes hacer esto

IF NOT EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   type = 'TR'
                    AND name = 'Insert_WithdrawalCodes' ) 
BEGIN
    EXEC ('CREATE TRIGGER Insert_WithdrawalCodes ON ...');
END;
 5
Author: Neel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-29 22:24:30

Compruebe SI Existe Para Trigger

IF EXISTS (SELECT * FROM sys.objects WHERE [name] = 
                 N'[Trigger_Name]' AND [type] = 'TR')
 BEGIN
 DROP TRIGGER [Trigger_Name]
 Print('Trigger dropped => [Schema].[Trigger_Name]')
 END
 GO

Compruebe SI existe para el procedimiento almacenado, Función también haciendo clic en el siguiente enlace http://www.gurujipoint.com/2017/05/check-if-exist-for-trigger-function-and.html

 0
Author: Jatin Phulera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-21 10:37:00