承诺外部交易

时间:2016-04-27 10:28:23

标签: sql sql-server tsql

请参阅下面的DDL:

create table  dbo.Test (id INT)

create PROCEDURE TestProcedure1
as
begin
    exec TestProcedure2
    insert into Test values (2)
end


create PROCEDURE TestProcedure2
as
begin

begin transaction
    insert into Test values (2)
end

现在运行:

exec TestProcedure1 commit

错误输出如下:

(1 row(s) affected)
Msg 266, Level 16, State 2, Procedure TestProcedure2, Line 0
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.

(1 row(s) affected)
Msg 266, Level 16, State 2, Procedure TestProcedure1, Line 0
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.

我理解错误的原因,即TestProcedure2中没有结束事务。这有什么影响?看到错误后,我运行了下面的SQL语句:

select * from dbo.Test

这返回了两行,即外部事务提交了内部事务。我有两个问题:

1) Does the outer transaction always commit the inner transaction.
2) After executing the select statement I executed the following commands:

commit
commit

What affect does running two commit statements have in this scenario?

1 个答案:

答案 0 :(得分:0)

  1. 是的,如果外部承诺,内心也承诺。如果外部回滚,所有内部回滚
  2. 您必须对所有commit运营商
  3. 使用begin tran运营商

    最好阅读本文以了解嵌套事务:https://technet.microsoft.com/en-us/library/ms189336(v=sql.105).aspx

相关问题