SQL經典編程

Use pubs
GO
declare @del_error int,@ins_error int

--開始事務
Begin tran
--執行刪除命令
Delete authors
Where au_id ='409-56-1688'

--捕獲執行完刪除操作后的@@error變量的值
Select @del_error = @@error
--執行插入操作
insert authors
values ('409-56-1688','Bennet','Abraham','416 658-9932','6223 Bateman ST.','Berkeley','CA','94160','1')
--捕獲執行完插入操作后的@@error變量的值
select @ins_error=@@error
--測試捕獲到的@@error值
if @del_error = 0 and @ins_error =0
Begin

--成功執行確定事務的操作
print 'The author information has been replaced'
commit tran
End
Else
Begin
--有錯誤發生,檢查究竟是那個語句有問題
--如何回滾整個事務

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

這個列子的一個事務中包含了2個操作,程序在每次數據庫操作后都檢查了@@error全局變量的值。如果2個操作都正常結束,則確定這個事務。但如果有1個操作出現錯誤,則回滾整個事務,使2個操作都不成功。
這個列子具有很強的代表性,因為類似的問題在數據庫編程過程中會經常用到

posted on 2008-03-31 15:12  子非魚  阅读(132)  评论(0编辑  收藏  举报