+1 for both of the above answers.
However, if you do not want to use TRY .. CATCH, try the following code. The part between the lines ----- is a test, and above and below that tSQLt represents, before and after it calls your test. As you can see, the transaction started by tSQLt before invoking the test still exists, as expected, regardless of whether an error occurs. @@ TRANSCOUNT is still 1
You can comment on RAISERROR to try it without exception.
SET NOCOUNT ON BEGIN TRANSACTION -- DONE BY tSQLt PRINT 'Inside tSQLt before calling the test: @@TRANCOUNT = ' + CONVERT (VARCHAR, @@TRANCOUNT) --------------------------------- PRINT ' Start of test ---------------------------' SAVE TRANSACTION Savepoint PRINT ' Inside the test: @@TRANCOUNT = ' + CONVERT (VARCHAR, @@TRANCOUNT) BEGIN TRANSACTION -- PART OF THE TEST PRINT ' Transaction in the test: @@TRANCOUNT = ' + CONVERT (VARCHAR, @@TRANCOUNT) RAISERROR ('A very nice error', 16, 0) PRINT ' @@ERROR = ' + CONVERT(VARCHAR,@@ERROR) -- PART OF THE TEST - CLEAN-UP IF @@ERROR <> 0 ROLLBACK TRANSACTION Savepoint -- Not all the way, just tothe save point ELSE COMMIT TRANSACTION PRINT ' About to finish the test: @@TRANCOUNT = ' + CONVERT (VARCHAR, @@TRANCOUNT) PRINT ' End of test ---------------------------' --------------------------------- ROLLBACK TRANSACTION -- DONE BY tSQLt PRINT 'Inside tSQLt after finishing the test: @@TRANCOUNT = ' + CONVERT (VARCHAR, @@TRANCOUNT)
With confirmation of information and code at http://www.blackwasp.co.uk/SQLSavepoints.aspx
source share