TSQL事务-提交和回滚
我有两个程序:TSQL事务-提交和回滚,tsql,transactions,Tsql,Transactions,我有两个程序: create procedure P2 as begin print @@trancount begin tran if 1 = 1 begin print @@trancount rollback end else begin commit end end go create procedure P1 as begin begin tran
create procedure P2
as
begin
print @@trancount
begin tran
if 1 = 1
begin
print @@trancount
rollback
end
else
begin
commit
end
end
go
create procedure P1
as
begin
begin tran
print @@trancount
exec P2
print @@trancount
commit
end
go
exec P1
当我打电话给P1时,我得到:
1
1
2
Msg 266, Level 16, State 2, Procedure P2, Line 0
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0.
0
Msg 3902, Level 16, State 1, Procedure P1, Line 8
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
我期望的结果是这样的:
1
1
2
1
我的问题是:
1. Why do I got this error?
2. How should I write my procedure to do it good?
当过程P2执行回滚行时,您正在回滚最外层的事务。最初在P1中创建的事务将更改从调用P2之前到执行之后的事务计数
如果希望某个过程影响事务计数,则可以在中调用该过程,以便能够处理返回的信息性消息
发件人:
您可能还想看看上的文章。当您的过程P2执行回滚行时,您正在回滚最外层的事务。最初在P1中创建的事务将更改从调用P2之前到执行之后的事务计数
如果希望某个过程影响事务计数,则可以在中调用该过程,以便能够处理返回的信息性消息
发件人:
您可能还想看看关于的文章
In stored procedures, ROLLBACK TRANSACTION statements without a savepoint_name
or transaction_name roll back all statements to the outermost BEGIN TRANSACTION.
A ROLLBACK TRANSACTION statement in a stored procedure that causes @@TRANCOUNT
to have a different value when the stored procedure completes than the
@@TRANCOUNT value when the stored procedure was called produces an informational
message. This message does not affect subsequent processing.
alter procedure P2 as
begin
print @@trancount
IF @@TRANCOUNT > 0
BEGIN
save tran SAVEPOINT1
END
ELSE
BEGIN
begin tran
END
if 1 = 1
begin
print @@trancount
IF XACT_STATE() <> -1
BEGIN
rollback tran SAVEPOINT1
END
end
else
begin
commit
end
end
go
alter procedure P1
as
begin
begin tran
print @@trancount
exec P2
print @@trancount
commit
end
go
exec P1