Warm tip: This article is reproduced from serverfault.com, please click

sql server-停止或中断 SQL 脚本的执行

(sql server - stop or break execution of a SQL script)

发布于 2009-03-18 17:04:20

有没有办法立即停止在 SQL 服务器中执行 SQL 脚本,例如“break”或“exit”命令?

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

Questioner
Andy White
Viewed
24
Blorgbeard 2017-07-19 00:43:00

RAISERROR方法

raiserror('Oh no a fatal error', 20, -1) with log

这将终止连接,从而停止运行脚本的其余部分。

请注意,WITH LOG要以这种方式工作,严重性级别 20 或更高以及该选项都是必需的。

这甚至适用于 GO 语句,例如。

print 'hi'
go
raiserror('Oh no a fatal error', 20, -1) with log
go
print 'ho'

会给你输出:

hi
Msg 2745, Level 16, State 2, Line 1
Process ID 51 has raised user error 50000, severity 20. SQL Server is terminating this process.
Msg 50000, Level 20, State 1, Line 1
Oh no a fatal error
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command.  The results, if any, should be discarded.

请注意,未打印 'ho'。

警告:

  • 这仅在你以管理员身份('sysadmin' 角色)登录时才有效,并且你也没有数据库连接。
  • 如果你不是以管理员身份登录,则 RAISEERROR() 调用本身将失败,脚本将继续执行
  • 使用 sqlcmd.exe 调用时,将报告退出代码 2745。

参考:http : //www.mydatabasesupport.com/forums/ms-sqlserver/174037-sql-server-2000-abort-whole-script.html#post761334

noexec 方法

另一种适用于 GO 语句的方法是set noexec on. 这会导致跳过脚本的其余部分。它不会终止连接,但你需要noexec在执行任何命令之前再次关闭。

例子:

print 'hi'
go

print 'Fatal error, script will not continue!'
set noexec on

print 'ho'
go

-- last line of the script
set noexec off -- Turn execution back on; only needed in SSMS, so as to be able 
               -- to run this script again in the same session.