确定以下代码的输出
PRINT 'Before Transaction'
SELECT @@TRANCOUNT
BEGIN TRAN T1
PRINT 'After transaction T1 starts'
/* Value of @@TranCount is 1 */
SELECT @@TRANCOUNT
BEGIN TRAN T2 save TRAN T2
--save tran T2
PRINT 'After transaction T2 starts'
/* Value of @@TranCount is 2 */
SELECT @@TRANCOUNT
ROLLBACK TRAN T2
PRINT 'After transaction T2 roll backs'
/* Value of @@TranCount is still 2 as the rollback failed due to a error */
SELECT @@TRANCOUNT ---------[IT SHOUD BE 1,BUT WHY RESULT IS COMING AS 2?]
ROLLBACK TRAN T1
PRINT 'After transaction T1 roll backs'
/* Value of @@TranCount is 0 */
SELECT @@TRANCOUNT
输出不正确的原因是什么?
答案 0 :(得分:0)
来自MSDN
ROLLBACK TRANSACTION将@@ TRANCOUNT减少为0,除了 ROLLBACK TRANSACTION savepoint_name,不影响 @@ TRANCOUNT。
您的交易 T2 保存,因此ROLLBACK
对@@TRANCOUNT
无效。
如果您在事务T1上使用 ROLLBACK
,则@@Trancount
将重置为 ZERO
答案 1 :(得分:0)
答案在于您的代码,因为您使用了保存TRAN T2 ,事务T2得到保存并且回滚不会影响 @@ TRANCOUNT 值
尝试在SQL Server中多次运行以下查询....每次执行此查询时,您都会看到@@ TRANCOUNT的值增加1。
SELECT @@TRANCOUNT
BEGIN TRAN T2 save TRAN T2
PRINT 'After transaction T2 starts'
SELECT @@TRANCOUNT
ROLLBACK TRAN T2
PRINT 'After transaction T2 roll backs'
SELECT @@TRANCOUNT