有没有办法立即停止 SQL Server 中 SQL 脚本的执行,例如“中断”或“退出”命令?
我有一个脚本,它在开始执行插入之前执行一些验证和查找,并且我希望它在任何验证或查找失败时停止。
最佳答案
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。
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/