SQL-Server Triggers  «Prev  Next»

Create a SQL Server 2025 DELETE Trigger: Model Answer

Your response

No answer was submitted. You can still review the model answer below.

This is a 20-point self-assessment. Your SQL has not been executed or automatically graded. Compare it with the model and rubric.

Model trigger

After creating and populating the practice table on the exercise page, run this definition in its own batch:

CREATE TRIGGER dbo.trgDelete
ON dbo.Sales
AFTER DELETE
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    IF NOT EXISTS (SELECT 1 FROM deleted)
        RETURN;

    THROW 51040, 'Rows cannot be deleted from dbo.Sales.', 1;
END;
GO

Why the solution works

AFTER DELETE limits this trigger to DELETE statements. When it begins, the affected rows have been removed within the current transaction and their previous values are available in deleted. AFTER does not mean after COMMIT. A failed transaction can still be rolled back.

NOT EXISTS permits a DELETE that matches no rows. If any row exists in deleted, the same error path handles the whole statement, whether it affected one row or many. There is no row-by-row loop and no attempt to modify the logical deleted table.

THROW raises the specified application error and honors XACT_ABORT. With that setting enabled, the invalid transaction cannot be committed. When the caller catches the error, it must roll back any transaction that remains active; the test below does so. RAISERROR does not honor XACT_ABORT, so the legacy RAISERROR-only answer did not establish this behavior. See Microsoft's XACT_ABORT guidance.

SET NOCOUNT ON suppresses row-count messages from trigger statements. The error number 51040 is in the permitted user-defined range, and the final argument is the state, not a severity level. See THROW. GO is a client batch separator and is not part of the stored trigger body.

Test a rejected deletion

Run this test separately in the same practice database, with no transaction already open. It attempts to delete both setup rows, checks for error 51040, and rolls back any remaining transaction. An unexpected error is rethrown.

BEGIN TRY
    BEGIN TRANSACTION;

    DELETE FROM dbo.Sales
    WHERE SalesID IN (1, 2);

    THROW 51041, 'Test failed: the DELETE was not rejected.', 1;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0
        ROLLBACK TRANSACTION;

    IF ERROR_NUMBER() <> 51040
        THROW;

    SELECT ERROR_NUMBER() AS ErrorNumber,
           ERROR_MESSAGE() AS ErrorMessage;
END CATCH;

SELECT SalesID, SaleTotal
FROM dbo.Sales
ORDER BY SalesID;
GO

Expected: error number 51040 with the trigger's message, followed by the two original rows, SalesID 1 with 50.00 and SalesID 2 with 75.00. The test deliberately raises error 51041 if the DELETE unexpectedly succeeds, so a missing or disabled trigger cannot be mistaken for a passing test.

The caller owns this test transaction. It uses XACT_STATE() to avoid issuing ROLLBACK when no transaction remains. An uncommittable transaction requires a full rollback, not a rollback to a savepoint. See XACT_STATE.

Check the permitted operations

The following test performs a zero-row DELETE, an INSERT, and an UPDATE. The final ROLLBACK restores the fixture. Run it as a separate batch after the rejected-deletion test:

BEGIN TRY
    BEGIN TRANSACTION;

    DELETE FROM dbo.Sales WHERE SalesID = -1;

    INSERT INTO dbo.Sales (SalesID, SaleTotal)
    VALUES (3, 25.00);

    UPDATE dbo.Sales SET SaleTotal = 60.00 WHERE SalesID = 1;

    SELECT SalesID, SaleTotal
    FROM dbo.Sales
    ORDER BY SalesID;

    ROLLBACK TRANSACTION;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0
        ROLLBACK TRANSACTION;
    THROW;
END CATCH;
GO

Expected inside the transaction: rows (1, 60.00), (2, 75.00), and (3, 25.00), with no trigger error. After rollback, the original two rows remain. To check a single-row rejection, rerun the first test with WHERE SalesID = 1. These SQL examples have been reviewed against the documentation; they are not a transcript of execution on a SQL Server instance.

Self-assessment rubric

Check your answerPoints
Creates dbo.trgDelete on dbo.Sales with the correct heading5
Uses AFTER DELETE only, with a valid body and batch boundary5
Checks deleted as a set and returns for zero affected rows5
Sets XACT_ABORT ON and raises error 51040 with the specified message and state5

FOR DELETE is equivalent to AFTER DELETE in this context and is acceptable. An equivalent set-based check can also satisfy the rubric. Review the actual behavior of your solution as well as its syntax.

Scope of the rule

This is a DELETE-trigger exercise, not a complete access-control policy. TRUNCATE TABLE does not fire DELETE triggers, and sufficiently privileged users can alter or disable triggers. Production retention requirements also need appropriate permissions and administration controls. See CREATE TRIGGER.

Return to the exercise to revise your answer, or continue with implementing SQL Server triggers.


Blue Host 300by250Blue Host 300by250