A Rigger can "undo/undo" the action that triggers it?

Asked

Viewed 228 times

5

Example scenario

I have a table telefones where I have a Trigger that is fired while performing the instruction Insert.


Doubt

  • I can use the Trigger for verify a condition and before the return, "cancel" the action on the table that fired it?
  • Would have as set the "attention/error message" that the SQL will return?

(An example would be extremely important)

  • Yes and Yes but note that this is bad practice for several reasons. Good practice is to put business rules at the business rules layer and there decide whether or not the action should be carried out and give due feedback to the user

  • @Jean I agree with you, Rigger will practically always be a "patch". But in the case of third party systems that there is no possibility of change in the source, Trigger ends up saving! rs

  • @Josédiz has some suggestions?

1 answer

1


By the description you gave the ideal would use a trigger of the kind instead of:

ALTER TRIGGER tr_tabela ON tabela
INSTEAD OF INSERT AS
BEGIN
    SET NOCOUNT ON;

    IF -- Sua condição para o erro aqui
    BEGIN
        RAISERROR('Mensagem de erro.', 16, 1);
    END
    ELSE -- Insere 
    BEGIN
        INSERT tabela
        SELECT i.*
          FROM inserted i;
    END;
END;
GO

In the case of the above non-executable example the insertion will only be performed in the table if the IF don’t be satisfied.


INSTEAD OF

Specifies that the DML trigger will be executed instead of the trigger SQL statement, overriding the actions of the trigger statements. INSTEAD OF cannot be specified for DDL or logon triggers.

At most, a INSTEAD OF trigger per INSERT, UPDATE or DELETE statement can be set in a table or display. However, you can set views over views, where each one has its own trigger INSTEAD OF.

INSTEAD OF triggers are not allowed in updatable views that use WITH CHECK OPTION. SQL Server generates an error when a INSTEAD OF trigger is added to a specified updatable display WITH CHECK OPTION. The user must remove this option using ALTER VIEW before setting the INSTEAD OF trigger.

  • Very good, Sorack, very good! But this phrase of yours confused me and left me a little doubt "By the description you gave the ideal would be to use a Rigger of the type Instead of". So just to extinguish any minimal doubt: the instead of would be the "ideal" or would be the only way?

  • 1

    @In the case you described I believe the only way. In a scenario where you could make the call by a procedure I believe it would be ideal.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.