By the description you gave the ideal would be to use a trigger
of type 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 non-executable example above the insertion will only be performed in the table if the IF
condition is not 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 can not be specified for DDL or logon triggers.
At most, an INSTEAD OF trigger per INSERT, UPDATE, or DELETE statement can be set in a table or view. However, you can set views on views, where each has its own INSTEAD OF trigger.
The INSTEAD OF triggers are not allowed in updatable views that use WITH CHECK OPTION. SQL Server generates an error when an INSTEAD OF trigger is added to a specified updateable WITH CHECK OPTION. The user should remove this option using ALTER VIEW before setting the INSTEAD OF trigger.