My SQL-Server learning curve has been back-to-front and after several yrs I’m battling to use TRANSACTION code effectively.
If COMMIT TRANSACTION is not explicitly stated then at the point of ROLLBACK TRANSACTION if no errors have occurred in preceding code will the transaction then be committed? The question is in connection with a structure like the following:
USE MyDataBase;
GO
BEGIN TRANSACTION;
--complex query X here
ROLLBACK TRANSACTION; PRINT N'Rolled back the transaction.';
GO
…I thought ROLLBACK TRANSACTION was used in a situation where you do not want changes to be made to a db if an error has occured in the preceding script – in the above this would be X. If i wanted to explicitly state COMMIT TRANSACTION in the above then where should it be located?
To confuse myself even more I’ve got the following – why is it rolling back twice? Is an error occuring to create the ROLLBACK?
USE WHAnalysis;
GO
BEGIN TRANSACTION;
IF @@TRANCOUNT = 1
SELECT @@TRANCOUNT
--do a complex query here
ROLLBACK TRANSACTION; PRINT N'Rolled back the transaction.';
GO
No. The transaction will remain open and uncommitted until it is committed, which will probably eventually cause blocking on your database.
If transactions are nested, rollback will rollback to the beginning of the outer transaction, not the inner transaction – See http://msdn.microsoft.com/en-us/library/ms181299.aspx
I would consider a structure something like