使用ERROR_NUMBER函数;
Return Types
int
Return Value
When called in a CATCH block, ERROR_NUMBER
returns the error number of the error that caused the CATCH block to run.
ERROR_NUMBER
returns NULL when called outside the scope of a CATCH block.
Remarks
ERROR_NUMBER
supports calls anywhere within the scope of a CATCH block.
ERROR_NUMBER
returns a relevant error number regardless of how many times it runs, or where it runs within the scope of the CATCH
block. This contrasts with a function like @@ERROR, which only returns an error number in the statement immediately following the one that causes an error.
In a nested CATCH
block, ERROR_NUMBER
returns the error number specific to the scope of the CATCH
block that referenced that CATCH
block. For example, the CATCH
block of an outer TRY...CATCH construct could have an inner TRY...CATCH
construct. Inside that inner CATCH
block, ERROR_NUMBER
returns the number of the error that invoked the inner CATCH
block. If ERROR_NUMBER
runs in the outer CATCH
block, it returns the number of the error that invoked that outer CATCH
block.
这里注意的是,ERROR_NUMBER实际上就是sys.messages视图中的message_id字段,所以可以参照这个表了解sql server抛出异常的情况;
注意sys.messages视图中统一个message_id可能会有多条记录,因为存在不同的语言;