简体   繁体   English

回滚SQL事务时停止执行

[英]Stop execution when ROLLBACK an SQL transaction

Is there a way to stop executing code once I ROLLBACK a transaction in T-SQL? 一旦我在T-SQL中回滚事务,是否有办法停止执行代码? For example, in the code below I want 'Message 1' to print, but not 'Message 2'. 例如,在下面的代码中,我希望打印“消息1”,而不是“消息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. GO语句将批次分开,这意味着即使第一个错误发生,下一个批次也将运行。 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. 您可以查看GOTO ,并具有一个错误处理块。 Or you can just have a RETURN ; 或者,您可以只获得RETURN however, this needs to be within the same GO block 但是,这必须在同一GO块中

Example: 例:

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

will still return Test 2, but not test 1. 仍会返回测试2,但不会返回测试1。

In addition to Mike's statements about the GO keyword you could try something like this 除了Mike关于GO关键字的声明,您还可以尝试类似的方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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