mysql+nest+嵌套事务,SQL Server-存储过程中的嵌套事务

Lets say this is the situation:

[Stored Proc 1]

BEGIN

BEGIN TRANSACTION

...

exec sp 2

COMMIT

END

Now, if SP 2 - rolls back for whatever reason, does SP 1 - commit or rollback or throw exception?

Thanks.

解决方案

There are no autonomous transactions in SQL Server. You may see @@TRANCOUNT increase beyond 1, but a rollback affects the whole thing.

EDIT asked to point to documentation. Don't know of the topic that documents this explicitly, but I can show it to you in action.

USE tempdb;

GO

Inner proc:

CREATE PROCEDURE dbo.sp2

@trip BIT

AS

BEGIN

SET NOCOUNT ON;

BEGIN TRANSACTION;

PRINT @@TRANCOUNT;

IF @trip = 1

BEGIN

IF @@TRANCOUNT > 0

ROLLBACK TRANSACTION;

END

ELSE

BEGIN

IF @@TRANCOUNT > 0

COMMIT TRANSACTION;

END

PRINT @@TRANCOUNT;

END

GO

Outer proc:

CREATE PROCEDURE dbo.sp1

@trip BIT

AS

BEGIN

SET NOCOUNT ON;

BEGIN TRANSACTION;

PRINT @@TRANCOUNT;

BEGIN TRY

EXEC dbo.sp2 @trip = @trip;

END TRY

BEGIN CATCH

PRINT ERROR_MESSAGE();

END CATCH

PRINT @@TRANCOUNT;

IF @@TRANCOUNT > 0

COMMIT TRANSACTION;

PRINT @@TRANCOUNT;

END

GO

So now let's call it and let everything commit:

EXEC dbo.sp1 @trip = 0;

Results:

1

2

1

1

0

Now let's call it and roll back the inner procedure:

EXEC dbo.sp1 @trip = 1;

Results:

1

2

0

Transaction count after EXECUTE indicates a mismatching number

of BEGIN and COMMIT statements. Previous count = 1, current count = 0.

0

0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值