Thursday 10 March 2011

SQL Server @@ERROR Example

I've been informed that using @@ERROR isn't the most robust way of error checking. An old example would be the following;



BEGIN TRANSACTION
EXEC sp_deleteuser 1
IF @@ERROR != 0 --RollBack Transaction if Error..
BEGIN
ROLLBACK TRANSACTION
END
ELSE
BEGIN
COMMIT TRANSACTION --finally, Commit the transaction if Success..
END

Instead of using the above example, you should be using the following;



BEGIN TRY
BEGIN TRANSACTION
EXEC sp_deleteuser 1
IF @@TRANCOUNT > 0
COMMIT TRANSACTION
END TRY
BEGIN CATCH
--Return error if any
SELECT
@errNo = ERROR_NUMBER()
, @errMsg = ERROR_MESSAGE()
, @errSeverity = ERROR_SEVERITY()
, @errState = ERROR_STATE()
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION
--Raise the error
RAISERROR (@errMsg, @errSeverity, @errState)
END CATCH

No comments:

Post a Comment