sqlserver 版 try catch

博客介绍了在SQL中处理错误的方法,将可能出错的SQL写在begin try...end try之间,出错时程序会跳到对应的begin catch...end catch中执行错误处理SQL,且try..catch可嵌套。还提到在begin catch...end catch中可利用四个系统函数获取出错信息,并给出简单示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

格式

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'

b3f99037563483904a321c5acd39aff7176.jpg

当 @temp_date='2019-05-1322'

1c5c4bf4c6c97a5d3d92e183ab1ddf1d9b0.jpg

转载于:https://my.oschina.net/qingqingdego/blog/3051699

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值