Transactions Locks «Prev  Next»

Handling Transaction Errors - Exercise

Objective: Practice handling errors in your transactions using SQL Server.

Exercise scoring

This exercise is scored on whether your solution uses a safe, repeatable error-handling pattern that correctly rolls back work when the INSERT fails.

Instructions

Your task is to add error handling around the INSERT statement shown below. After the INSERT executes, your code must check for failure and, if needed, roll back the transaction and stop execution.

Use modern SQL Server error handling. In particular:

  • Wrap the transaction in TRY...CATCH.
  • If an error occurs, roll back the transaction in the CATCH block.
  • Optionally return error details using ERROR_MESSAGE() (or rethrow using THROW).
  • Do not leave a transaction open after an error.

Start from this base transaction:

BEGIN TRAN;
INSERT INTO Clients
  (CompanyName, AddressLine1, City, State, Zip, ContactLastName, ContactFirstName, ContactPhone)
VALUES
  ('Acme Limited', '400 Main Street', 'Chicago', 'IL', '60609', 'Jones', 'John', '1234567890');
COMMIT TRAN;

Hints

  • Your INSERT can fail for common reasons such as constraint violations (PRIMARY KEY/UNIQUE), CHECK constraints, NOT NULL columns, or data type/length issues.
  • In a CATCH block, use XACT_STATE() to determine whether the transaction must be rolled back.
  • When testing, change one value intentionally (for example, make a string too long for its column) and confirm your code rolls back cleanly.

Submitting the exercise

Type or paste your finished T-SQL into the box below, then click Submit to view the results page. Do not include any solution output beyond what your script returns (for example, a final SELECT of an error message is acceptable).