資源描述:
《SqlServer嵌套事務(wù)機(jī)制.docx》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫(kù)。
1、今天我們主研究一下SqlServer中嵌套事務(wù)使用。代碼能說(shuō)明大多數(shù)問(wèn)題,看代碼。1.嵌套事務(wù)提交原理測(cè)試[c-sharp]?viewplaincopy1.PRINT?'Trancount?before?transaction:?'?+?CAST(@@trancount?as?char(1))???2.??3.BEGIN?TRAN??4.PRINT?'After?first?BEGIN?TRAN:?'?+?CAST(@@trancount?as?char(1))??5.??6.BEGIN?TRAN??7.PRINT?'After?second?BEG
2、IN?TRAN:?'?+?CAST(@@trancount?as?char(1))??8.COMMIT?TRAN??9.??10.PRINT?'After?first?COMMIT?TRAN:?'?+?CAST(@@trancount?as?char(1))??11.COMMIT?TRAN??12.??13.PRINT?'After?second?COMMIT?TRAN:?'?+?CAST(@@trancount?as?char(1))??結(jié)果:Trancountbeforetransaction:0AfterfirstBEGINTRAN:1Afte
3、rsecondBEGINTRAN:2AfterfirstCOMMITTRAN:1AftersecondCOMMITTRAN:0我們可以得出:1.可以看到每一個(gè)BEGINTRAN語(yǔ)句都會(huì)使@@TRANCOUNT增加1;2.每一個(gè)COMMITTRAN語(yǔ)句都會(huì)使@@TRANCOUNT減少1;3.如前所述,一個(gè)值為0的@@TRANCOUNT意味著沒(méi)有打開(kāi)的事務(wù);4.因此,在@@TRANCOUNT值從1降到0時(shí)結(jié)束的事務(wù)發(fā)生在最外層事務(wù)提交的時(shí)候。2.嵌套事務(wù)回滾2.1?嵌套事務(wù)回滾最外面事務(wù),對(duì)內(nèi)部事務(wù)有什么影響?我們?cè)賮?lái)看一段代碼:[c-sharp]?vi
4、ewplaincopy1.--?創(chuàng)建臨時(shí)表??2.CREATE?TABLE?#TestTrans(Cola?INT?PRIMARY?KEY,??3.???????????????Colb?varchar(20)?NOT?NULL);??4./*?外部事務(wù)?*/??1.BEGIN?TRANSACTION?OutOfProc;??2.--內(nèi)部事務(wù)??3.????BEGIN?TRANSACTION?InProc??4.??????INSERT?INTO?#TestTrans?VALUES?(1,'aaaa');??5.????COMMIT?TRANSACT
5、ION?InProc;??6.??????7./*?回滾外部事務(wù),也會(huì)回滾內(nèi)部事務(wù)?*/??8.ROLLBACK?TRANSACTION?OutOfProc;??9.??10./*無(wú)數(shù)據(jù),1說(shuō)明最外層事務(wù)回滾,里面所有的事務(wù)都會(huì)回滾?*/??11.SELECT?*?FROM?#TestTrans;??12.??13.drop?table?#TestTrans??結(jié)果:沒(méi)有數(shù)據(jù)?,F(xiàn)在看來(lái):無(wú)論數(shù)據(jù)是否提交,只要最外層回滾了就會(huì)導(dǎo)致所有內(nèi)部所有嵌套類回滾。2.2嵌套事務(wù)回滾內(nèi)部嵌套事務(wù)呢?再看一段代碼:[c-sharp]?viewplaincopy1.-
6、-?創(chuàng)建臨時(shí)表??2.CREATE?TABLE?#TestTrans(Cola?INT?PRIMARY?KEY,??3.???????????????Colb?varchar(20)?NOT?NULL);??4./*?外部事務(wù)?*/??5.BEGIN?TRANSACTION?OutOfProc;??6.--內(nèi)部事務(wù)??7.????BEGIN?TRANSACTION?InProc??8.??????INSERT?INTO?#TestTrans?VALUES?(1,'aaaa');??9.????ROLLBACK?TRANSACTION?InProc;?
7、?10.??????11.????--內(nèi)部事務(wù)2??12.????BEGIN?TRANSACTION?InProc2??13.??????INSERT?INTO?#TestTrans?VALUES?(2,'222');??14.????COMMIT?TRANSACTION?InProc2;??15.??????16./*?提交外部事務(wù)?*/??17.COMMIT?TRANSACTION?OutOfProc;??18.??19./*出錯(cuò):內(nèi)部事務(wù)未回滾,內(nèi)部事務(wù)不能回滾,"找不到該名稱的事務(wù)或保存點(diǎn)。"?*/??20.SELECT?*?FROM?#Te
8、stTrans;??21.??22.drop?table?#TestTrans??結(jié)果:有異常信息:(1行受