SQL Server triggers - order of execution

前端 未结 10 1186
旧时难觅i
旧时难觅i 2020-12-16 09:39

Does anyone know how SQL Server determines the order triggers (of same type, i.e. before triggers) are executed. And is there any way of changing this so that I can specify

相关标签:
10条回答
  • 2020-12-16 10:28

    Use sp_Settriggerorder stored procedure, you can define the execution order of the trigger.

    sp_settriggerorder [ @triggername = ] ‘[ triggerschema. ] triggername’
    , [ @order = ] ‘value’
    , [ @stmttype = ] ’statement_type’
    [ , [ @namespace = ] { ‘DATABASE’ | ‘SERVER’ | NULL } ]
    

    The second parameter, “order” can take three values which means that it can take into account up-to three triggers.

    1. First – Trigger is fired first
    2. Last - Trigger is fired last
    3. None – Trigger is fired in random order.
    0 讨论(0)
  • 2020-12-16 10:29

    sp_settriggerorder only applies to AFTER triggers.

    0 讨论(0)
  • 2020-12-16 10:30

    The order is set by sql server, the only thing you can do is use a system sp (sp_settriggerorder) to set which trigger will fire first and which will fire last.

    Beyond setting the first and last triggers to fire, you can't modify or tell which order sql server will use. Therefore you will want to build your triggers so they do not rely on which order they are fired. Even if you determine the order they fire in today, it may change tomorrow.

    This information is based on Sql Server 2000, however I do not believe 2005/2008 act differently in this regard.

    0 讨论(0)
  • 2020-12-16 10:33

    Using SetTriggerOrder is fine, but if your code depends on a specific sequence of execution, why not wrap all your triggers into stored procedures, and have the first one call the second, the second call the third, etc.

    Then you simply have the first one execute in the trigger.

    Someone in the future will be grateful that they didn't have to dig around in a system table to determine a custom execution sequence.

    0 讨论(0)
提交回复
热议问题