EricZ EricZ - 12 days ago 5
SQL Question

Can not get @@ERROR after EXEC() with Error

Please see the following t-sql code

DECLARE @iError INT
EXEC('select * from sysobj')
SELECT @iError = @@ERROR
PRINT 'Error = ' + CAST(@iError AS VARCHAR(10))


After I run it, it returns error message, which is what I want.


Msg 208, Level 16, State 1, Line 1

Invalid object name 'sysobj'.

Error = 208


However, if I change the query

DECLARE @iError INT
EXEC('select * from sysobjects where ''c'' = 1')
SELECT @iError = @@ERROR
PRINT 'Error = ' + CAST(@iError AS VARCHAR(10))


The output will be


Msg 245, Level 16, State 1, Line 1

Conversion failed when converting the varchar value 'c' to data type int.


The problem is any code afer EXEC() is not executed.

In the real stored procedure, I have some code to handle the errors after PRINT. And none of those code executed in second case.

Could someone let me know why this happens?

I tested it on both SQL Server 2008 and 2005.

Thanks

Answer

Different errors will have different levels of abort and some of these can be controlled through the use of settings, like ARITHIGNORE and ANSI_WARNINGS.

I suggest reading the following article that explains all of this in great detail.

http://www.sommarskog.se/error-handling-I.html#whathappens

Statement-termination and Batch-abortion

These two groups comprise regular run-time errors, such as duplicates in unique indexes, running out of disk space etc. As I have already have discussed, which error that causes which action is not always easy to predict beforehand. This table lists some common errors, and whether they abort the current statement or the entire batch.

enter image description here

Comments