There is no reason to use @@ ERROR now: TRY / CATCH is much more reliable. To understand more, I recommend reading Erland Sommarskog, "Error Handling in SQL 2005 and Later," which is one of the final related articles.
In this case, without TRY / CATCH, some errors are interrupted: this means that the code stops and the error does not fall into the trap. This is fixed using TRY / CATCH, with the exception of compilation errors.
This template is from my previous answer. Nested stored procedures containing the TRY CATCH ROLLBACK template?
CREATE PROCEDURE [Name] AS SET XACT_ABORT, NOCOUNT ON DECLARE @starttrancount int BEGIN TRY SELECT @starttrancount = @@TRANCOUNT IF @starttrancount = 0 BEGIN TRANSACTION [...Perform work, call nested procedures...] IF @starttrancount = 0 COMMIT TRANSACTION END TRY BEGIN CATCH IF XACT_STATE() <> 0 AND @starttrancount = 0 ROLLBACK TRANSACTION RAISERROR [rethrow caught error using @ErrorNumber, @ErrorMessage, etc]
If you use SET XACT_ABORT ON (which, in my opinion, should be best practice), then in any CATCH block @@ trancount is zero. Thus, you can write to the logging table here, if you want, in addition to the error.
source share