What is the most portable way to check whether a trigger exists in SQL Server?

后端 未结 9 1776
醉酒成梦
醉酒成梦 2020-12-14 05:50

I\'m looking for the most portable method to check for existence of a trigger in MS SQL Server. It needs to work on at least SQL Server 2000, 2005 and prefe

相关标签:
9条回答
  • 2020-12-14 06:21

    Generated by Sql Server Management Studio:

    IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[RolesYAccesos2016_UsuariosCRM_trgAfterInsert]'))
    DROP TRIGGER [dbo].[RolesYAccesos2016_UsuariosCRM_trgAfterInsert]
    GO
    
    
    CREATE TRIGGER [dbo].[RolesYAccesos2016_UsuariosCRM_trgAfterInsert] 
    ON  [PortalMediadores].[dbo].[RolesYAccesos2016.UsuariosCRM]
    FOR INSERT
    AS  
    ...
    

    For select @@version

    Microsoft SQL Server 2008 R2 (RTM) - 10.50.1797.0 (X64) Jun 1 2011 15:43:18 Copyright (c) Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.1 (Build 7601: Service Pack 1) (Hypervisor)

    0 讨论(0)
  • 2020-12-14 06:23

    Are trigger names forced to be unique in SQL server?

    As triggers are by definition applied to a specific table would it not be more efficient to restrict the search to only the table in question?

    We have a database with over 30k tables in it all of which have at least one trigger and may have more (bad DB design - quite probably, but it made sense years ago and didn't scale well)

    I use

    SELECT * FROM sys.triggers 
    WHERE [parent_id] = OBJECT_ID(@tableName) 
    AND [name] = @triggerName
    
    0 讨论(0)
  • 2020-12-14 06:32

    I would use this syntax to check and drop trigger

    IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SCHEMA_NAME].[TRIGGER_NAME]') AND type in (N'TR'))
    DROP TRIGGER [SCHEMA_NAME].[TRIGGER_NAME]
    
    0 讨论(0)
提交回复
热议问题