views:

46

answers:

3

Is there a way to stop executing code once I ROLLBACK a transaction in T-SQL? For example, in the code below I want 'Message 1' to print, but not 'Message 2'.

BEGIN TRANSACTION
GO
PRINT 'Message 1'
ROLLBACK TRANSACTION
GO
PRINT 'Message 2'
GO
A: 

If it's in a SP or similar, you can use RETURN

Vidar Nordnes
+5  A: 

The GO statement is separating the batches, this means that even if the first one errors, the next batch will run. I'm assuming (and you know what that means...) that you're trying to circumvent if you've got an error.

You can look at GOTO, and have a error handling block. Or you can just have a RETURN; however, this needs to be within the same GO block

Example:

GO
  return
  SELECT 'Test 1'
GO
  SELECT 'Test 2'
GO

will still return Test 2, but not test 1.

Mike M.
+3  A: 

In addition to Mike's statements about the GO keyword you could try something like this

BEGIN TRY
 Begin Transaction
  print 'Message1'
  Select 1/0 --throws error
 Commit Transaction
 print 'Message2'
END TRY
BEGIN CATCH
 rollback transaction
END CATCH
TooFat