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.
None of these works with 'GO' statements. In this code, regardless of whether the severity is 10 or 11, you get the final PRINT statement.
Test Script:
Results:
The only way to make this work is to write the script without
GO
statements. Sometimes that's easy. Sometimes it's quite difficult. (Use something likeIF @error <> 0 BEGIN ...
.)If you are simply executing a script in Management Studio, and want to stop execution or rollback transaction (if used) on first error, then the best way I reckon is to use try catch block (SQL 2005 onward). This works well in Management studio if you are executing a script file. Stored proc can always use this as well.
You can alter the flow of execution using GOTO statements:
Thx for the answer!
raiserror()
works fine but you shouldn't forget thereturn
statement otherwise the script continues without error! (hense the raiserror isn't a "throwerror" ;-)) and of course doing a rollback if necessary!raiserror()
is nice to tell the person who executes the script that something went wrong.I would not use RAISERROR- SQL has IF statements that can be used for this purpose. Do your validation and lookups and set local variables, then use the value of the variables in IF statements to make the inserts conditional.
You wouldn't need to check a variable result of every validation test. You could usually do this with only one flag variable to confirm all conditions passed:
Even if your validation is more complex, you should only need a few flag variables to include in your final check(s).
This was my solution:
...