Skip to content
Advertisement

What’s the point of BEGIN TRANSACTION; … ROLLBACK;

I understand that a transaction will automatically roll back whenever an error occurs. I read up on this for T-SQL from Microsoft and I found this syntax:

BEGIN TRANSACTION;
    STATEMENT1;
    STATEMENT2;
    STATEMENT3;
ROLLBACK;

Why? If you intend to not do things anyway, why bother?
Specifically I found this here: https://docs.microsoft.com/en-us/sql/t-sql/language-elements/rollback-transaction-transact-sql?view=sql-server-2017#examples
But in other places as well.

Advertisement

Answer

The documentation link where you saw that is only for demonstration purposes. It is showing what happens when you begin a transaction, try to insert some rows and then roll it back. Then another insert statement is executed and the reader is supposed to get the idea of how transaction rollback works (by looking at the result set that only the second insert made it and the transaction that was rolled back didn’t affect the data).

Usually rolling back in the way you have written is used for testing purposes only, while developing for example.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement