How to rollback transaction on error in SQL Server?

How to rollback transaction on error in SQL Server?

In any transaction scenario, we have to rollback transaction on error in SQL execution. Using TRY-CATCH we can capture the exception occurred in a statement in the stored procedure and in the CATCH block we can rollback the transaction. Below is an example.

Which is an example of a SQL Server rollback?

It includes the following example that I think makes it clear and includes the frequently overlooked @@trancount which is needed for reliable nested transactions

When to print ERROR message and rollback transaction?

If it is there then show the error message and ROLLBACK TRANSACTION. Otherwise simply print the error message. We have kept our COMMIT TRANSACTION T script towards the last line of TRY block in order to make sure that it should commit the transaction (final change in the database) only after all the code in the TRY block has run successfully.

How to do a try / catch block in SQL?

I am trying to write an MS sql script that has a transaction and a try/catch block. If it catches an exception, the transaction is rolled back. If not, the transaction is committed. I have seen a few different websites saying to do it like this:

How does a ROLLBACK statement in a stored procedure work?

ROLLBACK TRANSACTION statements in stored procedures do not affect subsequent statements in the batch that called the procedure; subsequent statements in the batch are executed. ROLLBACK TRANSACTION statements in triggers terminate the batch containing the statement that fired the trigger; subsequent statements in the batch are not executed.

What happens when a ROLLBACK statement is issued in a trigger?

A ROLLBACK TRANSACTION statement in a stored procedure that causes @@TRANCOUNT to have a different value when the stored procedure completes than the @@TRANCOUNT value when the stored procedure was called produces an informational message. This message does not affect subsequent processing. If a ROLLBACK TRANSACTION is issued in a trigger:

Can a transaction be called from a stored procedure?

This is primarily intended to support transactions in stored procedures that can be called either from a process already in a transaction or from processes that have no active transaction.