是否有一种方法可以立即停止SQL服务器中SQL脚本的执行,如“break”或“exit”命令?
我有一个脚本,它在开始插入之前执行一些验证和查找,我希望它在任何验证或查找失败时停止。
是否有一种方法可以立即停止SQL服务器中SQL脚本的执行,如“break”或“exit”命令?
我有一个脚本,它在开始插入之前执行一些验证和查找,我希望它在任何验证或查找失败时停止。
当前回答
在SQL 2012+中,您可以使用THROW。
THROW 51000, 'Stopping execution because validation failed.', 0;
PRINT 'Still Executing'; -- This doesn't execute with THROW
从MSDN:
引发异常并将执行转移到TRY…CATCH构造的CATCH块…如果TRY…CATCH结构不可用,则会话结束。设置引发异常的行号和过程。级别设置为16。
其他回答
只需使用RETURN(它可以在存储过程内部和外部工作)。
在SQL 2012+中,您可以使用THROW。
THROW 51000, 'Stopping execution because validation failed.', 0;
PRINT 'Still Executing'; -- This doesn't execute with THROW
从MSDN:
引发异常并将执行转移到TRY…CATCH构造的CATCH块…如果TRY…CATCH结构不可用,则会话结束。设置引发异常的行号和过程。级别设置为16。
在过去,我们使用了以下语句:效果最好:
RAISERROR ('Error! Connection dead', 20, 127) WITH LOG
进一步细化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-------------
将它包含在try catch块中,然后执行将被转移到catch。
BEGIN TRY
PRINT 'This will be printed'
RAISERROR ('Custom Exception', 16, 1);
PRINT 'This will not be printed'
END TRY
BEGIN CATCH
PRINT 'This will be printed 2nd'
END CATCH;