SQL Server @@ERROR is a global variable that returns an error number if the last statement encountered an error.
It is must to trace it within just after the next line where the actual error occurred, otherwise, it will reset to 0.
It returns 0, if the last T-SQL statement encountered no errors.
The return type of @@ERROR function is integer.
Lets look at an example of @@ERROR in SQL.
@@ERROR function to detect the divide by zero error
Lets try to produce a custom error of divide by zero error.
As you can see, it gives an error of divide by zero and error number that is 8134 .
Lets check @@ERROR function just right after statement.
SELECT 1/0 SELECT @@ERROR
As you can see, It returns the error number for the last T-SQL statement executed that is 8134, which means divide by zero error occurred.
@@Error when no error occurred in last executed statement
It returns 0, if no error occurred in last executed statement.
SELECT 1/1 SELECT @@ERROR
@@ERROR with TRY…CATCH blocks
You can also use @@Error with TRY…CATCH block as shown in below T-SQL code.
begin try select 1/0 end try begin catch select @@error as errorcode end catch
1,056 total views, 1 views today