Sunday, February 26, 2012

error_number() won't return error code

hi all,

i have sql statement in ExecuteSQLTask, connecting to AdventureWorks

BEGIN TRY
insert into person.contacts(contactid) values (1);
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH;

i purposely put a table that does not exist in the database to catch
the error. however, the error number that is 208 won't appear, instead
the whole error message will be displayed.

if i change the query in try block to
insert into person.contact(contactid) values (1);

it'll return the error number 544, which is correct.

what did i do wrong?
thanks!

You did nothing wrong.

Try/Catch doesn't catch all errors, specifically compile time errors (there are a few others). Try running the following, "more obvious" compile time error. This compile time error won't be caught either, since the execution of the statements never happens.

BEGIN TRY

PRINT 'Inside Try-Block'

'This is not sql'

END TRY

BEGIN CATCH

SELECT error_number() as 'Error In Try Block'

END CATCH

|||

thanks jaegd for your reply.. it didn't say in BOL that try/catch doesn't catch all errors or maybe i left that out.

anyhow, my problem is not solved. is there an alternative where i can catch any errors that occur?

|||See the following BOL reference for the constructs which Try/Catch does not trap.
http://msdn2.microsoft.com/en-us/library/ms175976.aspx

However, To catch almost every error (including compile time and deferred name resolution errors), you can use dynamic SQL in combination with sp_executesql.

BEGIN TRY
DECLARE @.not_sql NVARCHAR(100)
SET @.not_sql = 'This is not sql'
EXEC sp_executesql @.not_sql

END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber
END CATCH

Note that almost every error is caught with this method, because broken client connections are not

trapped, hopefully for relatively obvious reasons (you have no

connection).|||thanks a lot jaegd

No comments:

Post a Comment