开发者

a PRINT 'Success' that screw up a begin trans/ begin try commit / end try?

So I just saw a weird behavior

In one script there is something like:

  begin transaction
  begin try

       stuff
       stuff
       stuff

       print 'commit'
       commit transaction
  end try
  begin catch
       print 'rollback'
       print error_message()
       rollback transaction
  end catch

thing is when this script in run, I see the print commit message but it does not make the commit and lock the tables/rows/etc

I have to manually run a commit by selecting the line and run it.

but if I do this

 begin transaction
  begin try

       stuff
       stuff
       stuff

       commit transaction
       print 'commit'
  end try
  begin catch
       print error_message()
       rollback transaction
       print 'rollback'
  end catch

开发者_Go百科(swapped the print and the commit)

it work fine.

anyone know why this would happen?


this works fine for me:

--create table t (rowid int)  --create one time before running script

begin transaction
  begin try

       insert into t values (1)
       print 'commit'
       print XACT_STATE()   --should be 1
       commit transaction
       print XACT_STATE()   --should be 0
  end try
  begin catch
       print ERROR_MESSAGE()
       rollback transaction
       print 'rollback'
  end catch

select * from t

output

commit
1
0
rowid
-----------
1

Close your SSMS window, open a new window, and then run your 1st script again, I'll bet you had an open transaction the first time you ran it, so you needed that extra COMMIT.

EDIT after OP comment:

run this exact script in a new connection to each database:

BEGIN TRY create table t (rowid int) END TRY BEGIN CATCH END CATCH

print 'A - XACT_STATE()='+ISNULL(CONVERT(varchar(10),XACT_STATE()),'')+', @@TRANCOUNT='+ISNULL(CONVERT(varchar(10),@@TRANCOUNT),'')

begin transaction
  begin try

       insert into t values (1)
       print 'commit'
       print 'B - XACT_STATE()='+ISNULL(CONVERT(varchar(10),XACT_STATE()),'')+', @@TRANCOUNT='+ISNULL(CONVERT(varchar(10),@@TRANCOUNT),'')
       commit transaction
       print 'C - XACT_STATE()='+ISNULL(CONVERT(varchar(10),XACT_STATE()),'')+', @@TRANCOUNT='+ISNULL(CONVERT(varchar(10),@@TRANCOUNT),'')
  end try
  begin catch
       print ERROR_MESSAGE()
       rollback transaction
       print 'rollback'
  end catch

print 'D - XACT_STATE()='+ISNULL(CONVERT(varchar(10),XACT_STATE()),'')+', @@TRANCOUNT='+ISNULL(CONVERT(varchar(10),@@TRANCOUNT),'')

select * from t

you should get this:

A - XACT_STATE()=0, @@TRANCOUNT=0

(1 row(s) affected)
commit
B - XACT_STATE()=1, @@TRANCOUNT=1
C - XACT_STATE()=0, @@TRANCOUNT=0
D - XACT_STATE()=0, @@TRANCOUNT=0
rowid
-----------
1

(1 row(s) affected)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜