格式
begin try
--SQL
end try
begin 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可以在多次使用,值是不变的。
下面是一个简单的小例子。
declare
@temp_date varchar(20),
@date datetime
begin try
set @temp_date=''
set @temp_date='2019-05-13'
set @date=CONVERT(datetime,@temp_date)
print '正确日期='+convert(varchar(20),@date,120)
end try
begin catch
print '日期转换错误 转换对象'+@temp_date
end catch
当 @temp_date='2019-05-13'
当 @temp_date='2019-05-1322'