views:

59

answers:

2

A rollback after an insert that contains an output statement fails with "The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION." If the output statement is removed, then it works. Is there an explanation for this behavior?

Example:

create table test(i integer primary key)
go
begin transaction
  insert into test (i) values (1)
  insert into test (i) output inserted.i values (1)
go
rollback -- Fails 
go

begin transaction
  insert into test (i) values (1)
  insert into test (i) values (1)
go
rollback -- Works
go
+2  A: 

I don't know why this happens. It looks like SET XACT_ABORT ON is being set implicitly

As a workaround on SQL Server 2005 SP3 we can do this if it's blocking you

create table test(i integer primary key)
go
DECLARE @foo TABLE (i int)
begin TRANSACTION
  insert into test (i) values (1)
  insert into test (i) output inserted.i INTO @foo values (1)
GO
rollback --OK
GO

Edit: It could be that the OUTPUT clause is undefined

gbn
Thanks, that works. I'll just write it off as yet another bug in SQL Server that must be worked around.
Patrik Simons
+1  A: 

FYI this works fine in SQL 2008, so it must have been corrected at some point.

bluefooted
There is something else going on. In some SQL 2008 it works, in others it doesn't work.select @@version:works: Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (X64) Jul 9 2008 14:17:44 ... Standard Edition (64-bit) on Windows NT 6.0 <X64> (Build 6001: Service Pack 1)fails: Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 ... Standard Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )works: Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 ... Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )
Patrik Simons
The problem was the compatibility level. It works with compatibility level 100 (SQL Server 2008) and fails for 90 and 80.
Patrik Simons
Ah, good to know. So that implies that it was "by design" :)
bluefooted