Developing Microsoft SQL Server Databases — Question 53

You use SQL Server to maintain the data used by applications at your company.
You need to run two separate SQL statements.
You must guarantee that the following three things happen:
Either BOTH statements succeed or BOTH statements fail as a batch.
If an error occurs on the first statement, SQL should not attempt to run the second statement.
Error information should be returned to the client.
What should you do?

Answer options

Correct answer: B

Explanation

The correct answer is B because it uses a TRY...CATCH block along with SET XACT_ABORT ON, ensuring that if an error occurs in Statement 1, the transaction is rolled back, and no attempt is made to execute Statement 2, while also returning error information to the client. Options A and D do not use the TRY...CATCH structure, which is necessary for error handling, and Option C does not set XACT_ABORT ON, which may lead to incomplete transaction handling.