Is there a way to immediately stop execution of a SQL script in SQL server, like a “break” or “exit” command?
I have a script that does some validation and lookups before it starts doing inserts, and I want it to stop if any of the validations or lookups fail.
The raiserror method
This will terminate the connection, thereby stopping the rest of the script from running.
Note that both severity level 20 or higher and the
WITH LOGoption are necessary for it to work this way.This even works with GO statements, eg.
Will give you the output:
Notice that ‘ho’ is not printed.
CAVEATS:
Reference: http://www.mydatabasesupport.com/forums/ms-sqlserver/174037-sql-server-2000-abort-whole-script.html#post761334
The noexec method
Another method that works with GO statements is
set noexec on(docs). This causes the rest of the script to be skipped over. It does not terminate the connection, but you need to turnnoexecoff again before any commands will execute.Example: