Skip to content
Home » SQL Server @@ERROR

SQL Server @@ERROR

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.

SYNTAX

SELECT @@ERROR

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.

SELECT 1/0

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

 

Also Read.

TRY..CATCH




Loading

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from SQL Skull

Subscribe now to keep reading and get access to the full archive.

Continue reading