Увеличивает ли UPDATE @@ trancount на 1? - PullRequest
1 голос
/ 30 апреля 2019

Я понимаю, что 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

В примереЯ написал, что это неявная транзакция с примененным уловом начала / попытки.Как @@Trancount работает в этом сценарии?Увеличивает ли оператор Update его на 1, а автоматическая фиксация - на 1, оставляя @@trancount = 0?

1 Ответ

1 голос
/ 30 апреля 2019

Какое влияние оказывает [оператор 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...