How to add “IF NOT EXISTS” to create trigger statement

后端 未结 4 803
无人及你
无人及你 2021-01-01 09:03

I am using sql server 2008 R2. More specifically, Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) Apr 2 2010 15:48:46 Copyright (c) Microsoft Corporation Stan

4条回答
  •  渐次进展
    2021-01-01 09:07

    As other answers above not mentioned an important point I wrote this answer:

    • When we want to find a trigger or another object in sys.objects table, it is better to check accurately (with schema or object_id, etc) in where clause to avoid same name invalid results. Consider when another trigger with the same name already exists in another schema... Therefore, because the sys.object table contains an schema_id column, we can use it in addition to name and type columns to query more accurately as I provided as example below.

    • As Microsoft docs mentioned here under "Trigger Limitations":

    CREATE TRIGGER must be the first statement in the batch and can apply to only one table.

    therefore we use EXECUTE to overcome this limitation:

    IF NOT EXISTS (select * from sys.objects where schema_id=SCHEMA_ID('dbo') AND type='TR' and name='Insert_WithdrawalCodes')
    BEGIN
       EXECUTE ('CREATE TRIGGER [Insert_WithdrawalCodes] ON [dbo].[PupilWithdrawalReason]
       AFTER INSERT
       AS 
       BEGIN
          SET NOCOUNT ON;
          ...
       END');
    END
    

提交回复
热议问题