UPDATE是否将@@ trancount递增1?

时间:2019-04-30 20:12:25

标签: sql-server update-statement

我了解到BEGIN TRAN使@@trancount递增1,而COMMIT TRAN递减@@trancount递增1,但是UPDATE语句又如何呢?它有什么作用,特别是在隐式事务中?

我在https://docs.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017查找了信息 但从未提及UPDATE语句。

BEGIN TRY

    UPDATE cad
    SET [AccountExpirationDate] = DATEADD(MONTH, -13, [AccountExpirationDate])
    FROM [dbo].[CardActivationDetail] cad
    WHERE ci.[CardOrderId] = @CardOrderId;

END TRY
BEGIN CATCH
    IF @@trancount > 0
        ROLLBACK TRANSACTION;
END CATCH

在我发布的示例中,这是一个应用了begin / try catch的隐式事务。 @@Trancount在这种情况下如何工作?

Update语句是否将其递增1,而自动提交将其递减1,从而保留@@trancount = 0

1 个答案:

答案 0 :(得分:1)

  

[DML语句]对@@ trancount有什么影响,尤其是在隐式事务中?

启用隐式事务后,如果@@ trancount = 0,则它将@@ trancount递增两次,运行并将其递减1,然后在触发器之后运行,将其保留为1。

关闭隐式事务后,如果@@ trancount = 0,则它将@@ trancount递增两次,运行并递减1,运行所有AFTER触发器,然后再次递减,确认。

在任一情况下,如果@@ trancount> 0,则它将@@ trancount递增1,然后运行,递减1,然后再运行任何AFTER触发器。

您可以在死锁图中以及通过在DML中使用@@ trancount来查看此行为。

例如:

use tempdb
drop table if exists t
set nocount on
go
create table t(id int identity, a int)

go
create trigger tt on t after insert
as
begin
  select @@trancount trancount_in_trigger
end
go
set implicit_transactions off
go
if @@trancount > 0 rollback
go
print '---autocommit----'
select @@trancount trancount_before
insert into t(a) values (@@trancount)
select a trancount_during from t where id = SCOPE_IDENTITY()
select @@trancount trancount_after

go

begin transaction
print '---explicit transaction----'
select @@trancount trancount_before
insert into t(a) values (@@trancount)
select a trancount_during from t where id = SCOPE_IDENTITY()
select @@trancount trancount_after

commit

go

begin transaction
begin transaction
print '---explicit nested transaction----'
select @@trancount trancount_before
insert into t(a) values (@@trancount)
select a trancount_during from t where id = SCOPE_IDENTITY()
select @@trancount trancount_after

commit
commit

go 

set implicit_transactions on

go
print '---implicit transaction----'
select @@trancount trancount_before
insert into t(a) values (@@trancount)
select a trancount_during from t where id = SCOPE_IDENTITY()
select @@trancount trancount_after

commit

输出

---autocommit----
trancount_before
----------------
0

trancount_in_trigger
--------------------
1

trancount_during
----------------
2

trancount_after
---------------
0

---explicit transaction----
trancount_before
----------------
1

trancount_in_trigger
--------------------
1

trancount_during
----------------
2

trancount_after
---------------
1

---explicit nested transaction----
trancount_before
----------------
2

trancount_in_trigger
--------------------
2

trancount_during
----------------
3

trancount_after
---------------
2

---implicit transaction----
trancount_before
----------------
0

trancount_in_trigger
--------------------
1

trancount_during
----------------
2

trancount_after
---------------
1