SQL SERVER 里的 try catch

sql server 2005中新增加的try catch,可以很容易捕捉异常了

基本用法:

begin try
     {  sql_statement |
 statement_block  }
end try
begin catch
     {  sql_statement |
 statement_block }
end catch


注意:sql server只捕捉那些不是严重的异常,当比如数据库不能连接等这类异常时,是不能捕捉的一个例子:



BEGIN TRY
 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;
 


另外try catch可以嵌套


begin try
  delete from grandparent where name = 'john smith'
  print 'grandparent deleted successfully'
end try
begin catch
   print 'error deleting grandparent record'
   begin try
     delete from parent where grandparentid =
     (select distinct id from grandparent where name = 'john smith')
     print 'parent deleted successfully'
   end try
   begin catch
     print 'error deleting parent'
     begin try
       delete from child where parentid =
     (select distinct id from parent where grandparentid =
     (select distinct id from grandparent where name = 'john smith'))
       print 'child deleted successfully'
     end try


     begin catch
       print 'error deleting child'
     end catch
   end catch
 end catch


另外,sql server 2005在异常机制中,提供了error类的方法方便调试,现摘抄如下:

error_number(): returns a number associated with the error.

error_severity(): returns the severity of the error

.error_state(): returns the error state number associated with the error.

error_procedure(): returns the name of the stored procedure or trigger in which the error occurred.

error_line(): returns the line number inside the failing routine that caused the error.

error_message(): returns the complete text of the error message. the text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.


最后举例子如下,使用了error类的方法

BEGIN TRY
 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;
 


print 'command after try/catch blocks'


输出error detected


err_num err_sev err_state err_proc             err_line  err_msg
------- ------- --------- -------------------- --------- --------------------------------
8134        16          1 null                 4        divide by zero error encountered.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值