Какое влияние оказывает [оператор DML] [на @@ trancount], особенно в неявных транзакциях?
Если включен implicit_transactions, если @@ trancount = 0, то он увеличивается @@trancount дважды, запускает и уменьшает его на единицу, запускает любой после триггера, оставляя его равным 1.
При отключенном implicit_transactions, если @@ trancount = 0, он увеличивает @@ trancount дважды, запускает и уменьшает его на единицу, запускает любые триггеры AFTER и снова уменьшает его, фиксируя.
В любом случае, если @@ trancount> 0, он увеличивает @@ trancount на единицу, запускает, уменьшает его на единицу, запускает любые триггеры AFTER.
Это поведение можно увидеть на графиках взаимоблокировок и с помощью @@ trancount в вашем DML.
например:
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
output
---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