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.
IMPLICIT_TRANSACTIONS OFF
@@TRANCOUNT = 0
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.
dbo.Clients
CompanyName
NOT NULL
Add SET XACT_ABORT ON and TRY...CATCH error handling to this base transaction:
SET XACT_ABORT ON
TRY...CATCH
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;
BEGIN TRANSACTION
TRY
CATCH
THROW;
NULL
'Acme Limited'
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.
XACT_STATE()
This exercise uses an unscored self-assessment checklist.
XACT_STATE() <> 0
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.