@@error problem

  • I am trying to catch an error in a script, but apparently it doesn't work. 

     

    Set xact_abort off

    declare @intserialnumber as varchar(128)

    select * from customerproducts where serialnumber = cast('MNO0101             ' as int)

    if @@ERROR <> 0

    begin

     print 'failed'

    end

    results:

    Server: Msg 245, Level 16, State 1, Line 3

    Syntax error converting the varchar value 'MNO0101             ' to a column of data type int.

    Any ideas?

  • @@ERROR changes with each successive action.  Create another @Variable and capture @ERROR for display. 

     

    I wasn't born stupid - I had to study.

  • I am still having problems.

    declare @intserialnumber  int

    declare @myerror  int

    set @intserialnumber = cast('MNO0101             ' as int)

    select @myerror = @@error

    print @myerror

    Once the cast runs, I get the error immediately.

  • As message 245 has a severity level of 16, this causes the batch to terminate and you cannot trap the error message.

    Try instead:

    declare @serialString varchar(128)

    , @SerialNumber integer

    set @serialString = 'MNO0101 '

    IF 1 IsNumeric( @serialString )

    BEGIN

    print 'failed'

    RETURN +1

    END

    SET @SerialNumber = CAST(@serialString as integer)

    select * from customerproducts

    where serialnumber = @SerialNumber

    SQL = Scarcely Qualifies as a Language

  • Beautiful!  Thanks.  I've been stressing over a very heavy logic oriented script.  I should of thought of this.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply