1、今天我们主研究一下SqlServer中嵌套事务使用。代码能说明大多数问题,看代码。1.嵌套事务提交原理测试[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)) 结果:Trancountbeforetransaction:0AfterfirstBEGINTRAN:1Afte
3、rsecondBEGINTRAN:2AfterfirstCOMMITTRAN:1AftersecondCOMMITTRAN:0我们可以得出:1.可以看到每一个BEGINTRAN语句都会使@@TRANCOUNT增加1;2.每一个COMMITTRAN语句都会使@@TRANCOUNT减少1;3.如前所述,一个值为0的@@TRANCOUNT意味着没有打开的事务;4.因此,在@@TRANCOUNT值从1降到0时结束的事务发生在最外层事务提交的时候。2.嵌套事务回滚2.1 嵌套事务回滚最外面事务,对内部事务有什么影响?我们再来看一段代码:[c-sharp] vi
4、ewplaincopy1.-- 创建临时表 2.CREATE TABLE #TestTrans(Cola INT PRIMARY KEY, 3. Colb varchar(20) NOT NULL); 4./* 外部事务 */ 1.BEGIN TRANSACTION OutOfProc; 2.--内部事务 3. BEGIN TRANSACTION InProc 4. INSERT INTO #TestTrans VALUES (1,'aaaa'); 5. COMMIT TRANSACT