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

标签 sql sql-server scripting exit

有没有办法立即停止 SQL Server 中 SQL 脚本的执行,例如“中断”或“退出”命令?

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

最佳答案

raiserror方法

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

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

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

这甚至适用于 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 ( docs )。这会导致脚本的其余部分被跳过。它不会终止连接,但您需要在执行任何命令之前再次关闭 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.

关于SQL Server - 停止或中断 SQL 脚本的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/659188/

相关文章:

linux - 在 Linux 中快速简单的 GUI 编程

php - 字段电子邮件未在 MySQL 表中更新(使用 PDO)

mysql - Codeigniter 在 SQL 中插入多行

mysql - 如何在 MySQL 的 INSERT 语句中使用 SELECT MAX?

sql-server - 为什么 ROW_NUMBER() 在 SQL Server 2008 中无法识别?

linux - shell脚本这行代码是什么意思

xcode - 使用脚本将文件添加到 Xcode 目标

sql - Codeigniter 事件记录所在数组

mysql - 在线通讯应用程序

超过 100 万行的 SQL Server BULK INSERT - 需要性能改进