Transactions Locks «Prev  Next»

Handling Transaction Errors - Exercise

Objective: Handle a failed client insert without committing incomplete work or leaving a transaction open.

Prerequisites: Use a disposable SQL Server practice database and a session with IMPLICIT_TRANSACTIONS OFF and @@TRANCOUNT = 0 before starting. This exercise owns the entire transaction; it is not a nested-transaction or savepoint template.

Assume dbo.Clients already exists with the eight columns below, all long enough for the supplied strings. CompanyName is NOT NULL. Any omitted key is generated automatically, and other omitted required columns have defaults. Assume this new client satisfies all other constraints. Adjust the practice schema before testing if these assumptions do not hold.

Instructions

Add SET XACT_ABORT ON and TRY...CATCH error handling to this base transaction:

BEGIN TRANSACTION;
INSERT INTO dbo.Clients
    (CompanyName, AddressLine1, City, State, Zip,
     ContactLastName, ContactFirstName, ContactPhone)
VALUES
    ('Acme Limited', '400 Main Street', 'Chicago', 'IL', '60609',
     'Jones', 'John', '1234567890');
COMMIT TRANSACTION;
  1. Keep BEGIN TRANSACTION, the insert, and the success-only commit inside TRY.
  2. In CATCH, roll back any active transaction and rethrow the caught error with THROW;.
  3. Describe two independent tests: the valid insert shown and an insert with NULL instead of 'Acme Limited'. For the failed test, state what happens to the attempted row and transaction count.

Hints

Use XACT_STATE() to avoid issuing a rollback when no transaction remains. A simple error-message result set is not equivalent to propagating an exception to the caller. Run the failure test against a reset practice dataset so a prior successful insert cannot confuse the result.

Self-assessment checklist

This exercise uses an unscored self-assessment checklist.

  • Start the transaction inside TRY with SET XACT_ABORT ON.
  • Commit only if the insert succeeds.
  • In CATCH, roll back when XACT_STATE() <> 0.
  • Use THROW; after rollback to propagate the original error.
  • Explain the valid insert and the NULL company-name test, including the absence of an open transaction afterward.

Submit your answer

Paste your T-SQL and expected test results below, then select Submit to compare them with the model solution. The website does not execute SQL.