用 @@ERROR 检测几条语句的成功

本文通过一个具体的SQL示例展示了如何使用@@ERROR函数来检查事务中DELETE和INSERT操作是否成功。通过设置局部变量来捕获每次操作后的错误值,以此决定是提交还是回滚事务。

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

用 @@ERROR 检测几条语句的成功

下面的示例取决于 INSERT 和 DELETE 语句的成功操作。局部变量在两条语句后均被设置为 @@ERROR 的值,并且用于此操作的共享错误处理例程中。

USE pubs
GO
DECLARE @del_error int, @ins_error int
-- Start a transaction.
BEGIN TRAN
-- Execute the DELETE statement.
DELETE authors
WHERE au_id = '409-56-7088'
-- Set a variable to the error value for
-- the DELETE statement.
SELECT @del_error = @@ERROR
-- Execute the INSERT statement.
INSERT authors
VALUES('409-56-7008', 'Bennet', 'Abraham', '415 658-9932',
'6223 Bateman St.', 'Berkeley', 'CA', '94705', 1)
-- Set a variable to the error value for
-- the INSERT statement.
SELECT @ins_error = @@ERROR
-- Test the error values.
IF @del_error = 0 AND @ins_error = 0
BEGIN
-- Success. Commit the transaction.
PRINT "The author information has been replaced"
COMMIT TRAN
END
ELSE
BEGIN
-- An error occurred. Indicate which operation(s) failed
-- and roll back the transaction.
IF @del_error <> 0
PRINT "An error occurred during execution of the DELETE
statement."
IF @ins_error <> 0
PRINT "An error occurred during execution of the INSERT
statement."
ROLLBACK TRAN
END
GO
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值