Trigger to reject or accept an update or insert

zoe Ohara 286 Reputation points
2022-04-07T11:17:53.137+00:00

Hi!

I have a requirement where I need to create a BEFORE INSERT, UPDATE trigger on a table. It needs to check a condition (various values don't already exist etc.) and then either ACCEPT or REJECT the transaction. Is this possible?

I would normally use a constraint on the table for this purpose, but for complex reasons that I wont go into I cant do this and need to use a trigger instead.

Thanks,

Zoe

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,556 questions
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 101.6K Reputation points MVP
    2022-04-07T22:04:16.293+00:00

    If you want to do this as an INSTEAD OF trigger, the INSERT trigger should look like this outline:

    CREATE TRIGGER MyTrigger ON MyTable INSTEAD OF INSERT AS
    
    IF NOT EXISTS (SELECT * FROM inserted) RETURN
    
    IF <bad condition is true>
    BEGIN
        RAISERROR('Blue murder!', 16, 1)  
        ROLLBACK TRANSACTION
        RETURN
    END
    
    INSERT tbl (col1, col2, col3, ....)
       SELECT col1, co2, col3, ...
       FROM  inserted
    

    Since repeating the INSERT statement is kind of boring and opens for a maintenance problem, most people do this as an AFTER trigger. But if you expect the bad condition to appear often, it cannot be denied that the INSTEAD OF trigger is more efficient.

    Note: Never do COMMIT TRANSACTION in a trigger, that will not end well!

    1 person found this answer helpful.
    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. zoe Ohara 286 Reputation points
    2022-04-08T17:04:55.027+00:00

    Thanks all!

    I've gone with Erlands answer as it allowed me to use the INSTEAD OF trigger

    0 comments No comments