SQL Server重溫 事務(wù)
發(fā)布日期:2022-01-14 12:34 | 文章來源:腳本之家
當(dāng)對(duì)多個(gè)表進(jìn)行更新的時(shí)候,某條執(zhí)行失敗。為了保持?jǐn)?shù)據(jù)的完整性,需要使用事務(wù)回滾。
顯示設(shè)置事務(wù)
復(fù)制代碼 代碼如下:
begin try
begin transaction
insert into shiwu (asd) values ('aasdasda');
commit transaction
end try
begin catch
select ERROR_NUMBER() as errornumber
rollback transaction
end catch
隱式設(shè)置事務(wù)
復(fù)制代碼 代碼如下:
set implicit_transactions on; -- 啟動(dòng)隱式事務(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
顯示事務(wù)以下語句不能使用,隱式事務(wù)可以
復(fù)制代碼 代碼如下:
alter database;
backup;
create database;
drop database;
reconfigure;
restore;
update statistics;
顯示事務(wù)可以嵌套使用
復(fù)制代碼 代碼如下:
--創(chuàng)建存儲(chǔ)過程
create procedure qiantaoProc
@asd nchar(10)
as
begin
begin try
begin transaction innerTrans
save transaction savepoint --創(chuàng)建事務(wù)保存點(diǎn)
insert into shiwu (asd) values (@asd);
commit transaction innerTrans
end try
begin catch
rollback transaction savepoint --回滾到保存點(diǎn)
commit transaction innerTrans
end catch
end
go
begin transaction outrans
exec qiantaoProc 'asdasd';
rollback transaction outrans
事務(wù)嵌套,回滾外層事務(wù)時(shí),如果嵌套內(nèi)的事務(wù)已經(jīng)回滾過則會(huì)有異常。此時(shí)需要使用事務(wù)保存點(diǎn)。如上代碼。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
相關(guān)文章