sql事務(wù)(Transaction)用法介紹及回滾實(shí)例
事務(wù)(Transaction)是并發(fā)控制的單位,是用戶定義的一個(gè)操作序列。這些操作要么都做,要么都不做,是一個(gè)不可分割的工作單位。通過事務(wù),
SQL Server能將邏輯相關(guān)的一組操作綁定在一起,以便服務(wù)器保持?jǐn)?shù)據(jù)的完整性 當(dāng)對多個(gè)表進(jìn)行更新的時(shí)候,某條執(zhí)行失敗。為了保持?jǐn)?shù)據(jù)的完整性,需要使用事務(wù)回滾。
顯示設(shè)置事務(wù) 代碼如下
begin try
begin transaction --開始事務(wù)
insert into shiwu (asd) values ('aasdasda');
commit transaction --提交事務(wù)
end try
begin catch
select ERROR_NUMBER() as errornumber
rollback transaction --事務(wù)回滾
end catch
隱式設(shè)置事務(wù) 代碼如下
set implicit_transactions on;
-- 啟動隱式事務(wù) go begin try
insert into shiwu (asd) values ('aasdasda');
insert into shiwu (asd) values ('aasdasda');
commit transaction;
end try begin catch
select ERROR_NUMBER() as errornumber
rollback transaction;
--回滾事務(wù) end catch set implicit_transactions off; --關(guān)閉隱式事務(wù)
go