使用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 CATCHblock 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_NUMBERreturns 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可能会有多条记录,因为存在不同的语言;
本文详细介绍了SQL Server中的ERROR_NUMBER函数,该函数用于返回触发CATCH块运行的错误编号。ERROR_NUMBER函数在CATCH块范围内任何位置均可调用,并返回与当前CATCH块相关的错误号,即使在嵌套CATCH块中也能准确返回引发该CATCH块执行的错误号。
2489

被折叠的 条评论
为什么被折叠?



