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

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


当前回答

进一步细化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(它可以在存储过程内部和外部工作)。

你可以使用RAISERROR。

我一直在使用以下脚本,你可以在我的回答中看到更多细节。

RAISERROR ( 'Wrong Server!!!',18,1) WITH NOWAIT RETURN
    
    print 'here'
    
    select [was this executed]='Yes'

如果你可以使用SQLCMD模式,那么咒语

:on error exit

(包括冒号)将导致RAISERROR实际停止脚本。例如,

:on error exit

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SOMETABLE]') AND type in (N'U')) 
    RaisError ('This is not a Valid Instance Database', 15, 10)
GO

print 'Keep Working'

将输出:

Msg 50000, Level 15, State 10, Line 3
This is not a Valid Instance Database
** An error was encountered during execution of batch. Exiting.

批次就会停止。如果SQLCMD模式未打开,则会得到关于冒号的解析错误。不幸的是,如果脚本没有在SQLCMD模式下运行,那么它并不是完全防弹的,SQL management Studio甚至可以轻松地跳过解析时间错误!不过,如果您从命令行运行它们,这是没问题的。

在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。