是否有一种方法可以立即停止SQL服务器中SQL脚本的执行,如“break”或“exit”命令?

我有一个脚本,它在开始插入之前执行一些验证和查找,我希望它在任何验证或查找失败时停止。


当前回答

将适当的代码块包装在try catch块中。然后,如果您愿意,可以使用严重程度为11的Raiserror事件,以便中断到catch块。如果你只想抛出错误,但在try块内继续执行,那么使用较低的严重程度。

试一试……抓住(transact - sql)

其他回答

进一步细化Sglasses方法,上面的代码行强制使用SQLCMD模式,如果不使用SQLCMD模式,则终止脚本,或者使用:on error exit在出现任何错误时退出 CONTEXT_INFO用于跟踪状态。

SET CONTEXT_INFO  0x1 --Just to make sure everything's ok
GO 
--treminate the script on any error. (Requires SQLCMD mode)
:on error exit 
--If not in SQLCMD mode the above line will generate an error, so the next line won't hit
SET CONTEXT_INFO 0x2
GO
--make sure to use SQLCMD mode ( :on error needs that)
IF CONTEXT_INFO()<>0x2 
BEGIN
    SELECT CONTEXT_INFO()
    SELECT 'This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!'
    RAISERROR('This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!',16,1) WITH NOWAIT 
    WAITFOR DELAY '02:00'; --wait for the user to read the message, and terminate the script manually
END
GO

----------------------------------------------------------------------------------
----THE ACTUAL SCRIPT BEGINS HERE-------------

我在这里一直使用RETURN,在脚本或存储过程中工作

如果您在事务中,请确保您ROLLBACK事务,否则立即RETURN将导致一个开放的未提交事务

只需使用RETURN(它可以在存储过程内部和外部工作)。

我不会使用RAISERROR- SQL有IF语句可以用于此目的。执行您的验证和查找并设置局部变量,然后使用IF语句中的变量值使插入具有条件。

您不需要检查每个验证测试的变量结果。你通常可以用一个标志变量来确认所有传递的条件:

declare @valid bit

set @valid = 1

if -- Condition(s)
begin
  print 'Condition(s) failed.'
  set @valid = 0
end

-- Additional validation with similar structure

-- Final check that validation passed
if @valid = 1
begin
  print 'Validation succeeded.'

  -- Do work
end

即使您的验证更复杂,您也应该只需要在最终检查中包含几个标志变量。

谢谢你的回答!

Raiserror()工作得很好,但你不应该忘记return语句,否则脚本将继续没有错误!(因此,raiserror不是一个“throwerror”;-)),当然,如果需要,还会进行回滚!

Raiserror()用于告诉执行脚本的人出错了。