简体   繁体   中英

Stop execution when ROLLBACK an SQL transaction

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

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.

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

如果在SP或类似版本中,则可以使用RETURN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM