begin try --SQL end trybegin catch --sql (处理出错动作) end catch
我们将可能会出错的sql 写在begin try...end try 之间,若出错,刚程序就跳到紧接着的begin try...end try 的beign catch...end catch
中,执行beign catch...end catch错误处理SQL。try..catch 是可以嵌套的。
在begin catch ...end catch中我们可以利用系统提供的下面四个函数得到出错信息:
error_number 返回错误代码
error_serverity 返回错误的严重级别
error_state 返回错误状态代码
error_message 返回完整的错误信息
上面的四个函数在同一个begin catch ...end catch可以在多次使用,值是不变的。
下面是一个简单的小例子。
begin try select 2/0 end try
begin catch select error_number() as error_number , error_message() as error_message, error_state() as error_state, error_severity() as error_severity end catch
结果:
----- error_number error_message error_state error_severity
8134 遇到以零作除数错误。 1 16
-------------------------------------------------------
不受 TRY…CATCH 构造影响的错误 TRY…CATCH 构造在下列情况下不捕获错误:
严重级别为 10 或更低的警告或信息性消息。
严重级别为 20 或更高且终止会话的 SQL Server 数据库引擎任务处理的错误。 如果所发生错误的严重级别为 20 或更高,而数据库连接未中断,则 TRY…CATCH 将处理该错误。
需要关注的消息,如客户端中断请求或客户端连接中断。
当系统管理员使用 KILL 语句终止会话时。
USE AdventureWorks; GO
BEGIN TRY -- Generate a divide-by-zero error. SELECT 1/0; END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage; END CATCH; GO
USE AdventureWorks; GO BEGIN TRANSACTION;
BEGIN TRY -- Generate a constraint violation error. DELETE FROM Production.Product WHERE ProductID = 980; END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() as ErrorState, ERROR_PROCEDURE() as ErrorProcedure, ERROR_LINE() as ErrorLine, ERROR_MESSAGE() as ErrorMessage;
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; END CATCH;
IF @@TRANCOUNT > 0 COMMIT TRANSACTION; GO