[SQL]事務回滾詳解及示例

存儲過程當中的 SET XACT_ABORT ON 和事務

在存儲過程當中寫SET XACT_ABORT ON 有什麼用?

SET XACT_ABORT ON是設置事務回滾的!
當爲ON時,若是你存儲中的某個地方出了問題,整個事務中的語句都會回滾
爲OFF時,只回滾錯誤的地方
-----------------------------------------------------------------------------------------------
第一種狀況:每次成功執行一條語句就馬上進行提交事務 (注意commit tran的位置)
use sales --指定數據庫
go
 
alter table T_UserInfoTwo
add constraint ck_id check(id between 1 and 15) --給T_UserInfoTwo表的Id添加約束
go
 
if exists(select * from sys.objects where name='proc_userinfotwo_insert')
    drop proc proc_userinfotwo_insert --若是存在此存儲過程則刪除
go
 
create proc proc_userinfotwo_insert --建立存儲過程
as
begin
    declare @id int
    set @id=1
    while @id<20
    begin
        begin try
            begin tran --開啓事務(設置反悔點)
            insert into T_UserInfoTwo values(@id,'小雅',21,0,'18620005006','123@qq.com',' 湖南常德','朋友',1,'壞心眼女巫');        
            commit tran --提交事務(不反悔,將數據插入到表中)
        end try
        begin catch
            rollback tran --拋出異常後回滾
        end catch
 
        set @id    =@id+1;    --變量自增1
    end
end
go
-----------------------------------------------------------------------------------------------


第二種狀況,當循環插入數據的時候,只要拋出異常,以前全部的 操做都進行回滾 (注意commit tran的位置與第一種狀況是不同的)

use sales --指定數據庫 go alter table T_UserInfoTwo add constraint ck_id check(id between 1 and 15) --給T_UserInfoTwo表的Id添加約束 go if exists(select * from sys.objects where name='proc_userinfotwo_insert') drop proc proc_userinfotwo_insert --若是存在此存儲過程則刪除 go create proc proc_userinfotwo_insert --建立存儲過程 as begin declare @id int set @id=1 begin begin try begin tran --開啓事務(設置反悔點) while @id<20 begin insert into T_UserInfoTwo values(@id,'小雅',21,0,'18620005006','123@qq.com',' 湖南常德','朋友',1,'壞心眼女巫'); set @id =@id+1; --變量自增1 end commit tran --提交事務(不反悔,將數據插入到表中) 特別要注意這個commit tran的位置,不若是不想每執行完一條數據就提交事務,就應該講這個commit tran放到while循環外面來。 end try begin catch begin rollback tran --拋出異常後回滾 end end catch end end go
相關文章
相關標籤/搜索