can''t call sp_settriggerorder from an SP

  • Hello!

    I'm creating triggers from a trigger for auditing pourposes, and I need to be sure that the audit triggers are the last ones to be executed (in case some audited table has other triggers).

    I'm trying to use sp_settriggerorder, but it doesn't seem to work when called from a procedure. 

    This sequence does throw an error on my machine.

    Please, help. Am I doing something wrong?

    Thanks a lot

     

    IF NOT EXISTS (SELECT * FROM sysobjects WHERE name = 'Table1')

      CREATE TABLE Table1 (Cod int)

    GO

    IF EXISTS (SELECT * FROM sysobjects WHERE name = 'tI_Table1')

      DROP TRIGGER tI_Table1

    GO

    CREATE TRIGGER tI_Table1 ON Table1 FOR INSERT AS

      Print 'I''m a trigger!'

    GO   

    IF EXISTS (SELECT * FROM sysobjects WHERE name = N'sp_TriggerOrder')

      DROP PROCEDURE sp_TriggerOrder

    GO

    CREATE PROCEDURE sp_TriggerOrder

    AS

      sp_settriggerorder tI_Table1, 'Last', 'INSERT'

    GO

    Servidor: mensaje 170, nivel 15, estado 1, procedimiento sp_TriggerOrder, línea 4

    Line 4: Incorrect syntax near 'sp_settriggerorder'.

  • sp_settriggerorder @triggername= 'tI_Table1' /*quotes!*/,@order= 'Last', @stmttype ='INSERT'

    *second you can put SET NOCOUNT ON at the beginning of your triggers to reduce network traffic

  • Thanks for the reply.

    The quotes doesn't seem to be the problem.

    As a workarroud I EXECUTE the sp_settriggerorder call as a string. This seems to change the scope, and it works.

    IF NOT EXISTS (SELECT * FROM sysobjects WHERE name = 'Table1')

      CREATE TABLE Table1 (Cod int)

    GO

    IF EXISTS (SELECT * FROM sysobjects WHERE name = 'tI_Table1')

      DROP TRIGGER tI_Table1

    GO

    CREATE TRIGGER tI_Table1 ON Table1 FOR INSERT AS

      Print 'I''m a trigger!'

    GO   

    IF EXISTS (SELECT * FROM sysobjects WHERE name = N'sp_TriggerOrder')

      DROP PROCEDURE sp_TriggerOrder

    GO

    CREATE PROCEDURE sp_TriggerOrder

    AS

    DECLARE @SqlString varchar(200)

      SET @SqlString = 'sp_settriggerorder @triggername=''tI_Table1''

                                         , @order=''Last''

                                         , @stmttype=''INSERT'''

      Print @SqlString

      EXECUTE(@SqlString)

    GO

    Thanks!

  • when you call an SP and it is not the first line in the batch you need to use exec

    ...

    CREATE PROCEDURE sp_TriggerOrder

    AS

     exec sp_settriggerorder 'tI_Table1', 'Last', 'INSERT'

    GO

    ...


    * Noel

  • Thankx noeld

    That was it

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply