Sql Server - stop or break execution of a SQL script
Stop the show with a SQL script in SQL Server by using RAISERROR('Error Message', 11, 1) followed by RETURN. Now the script throws a tantrum with an error of amazing severity to stop the batch, and RETURN is like that end scene call in a play:
Keep in mind the diva RAISERROR stops only the current batch; position these strategically like laser tripwires.
Simple and effective ways to halt execution
Want to yell "Cut!" on a SQL script? These practical tools and considerations will let you become the director of your script's fate.
The subtle art of saying "cut!" with "set noexec on/off"
Send subtler cues to your SQL script with set noexec on, like whispering to it to quit the act. When ready for an encore, set noexec off queues the next scene:
Over to 'RETURN' for a quiet exit
Direct your scripts more subtly using RETURN, making exits happen as smoothly as leaves falling:
Local variables on the director's seat
IF clauses and local variables are your control panels for validation:
Special effects with "TRY...CATCH" blocks
Design dramatic twists paired with THROW, firing special effects on error:
"IF NOT EXISTS": The epic plot protector
Avoid narrative disasters with preventive checks before key scenes, ensuring your story remains consistent:
Control flow and error handling: Mastering the art
Take your error handling and control flow to the next level with advanced techniques and tools.
Scripting perfection in "SQLCMD mode"
When sqlcmd.exe is your stage, :on error exit ensures perfect performances:
Kiddie pool to swimming in the deep - structured flags
For more complex plays, a structured flag variable simplifies the drama:
New-age 'RAISERROR' for the non-admins
In scenarios where you're the director with no admin privileges:
Manage mini-plays within your script with 'GO'
Use GO to manage separate acts within the same script:
Audience interaction with 'THROW'
THROW allows you to engage your audience with tailored error messages:
Sharing the behind-the-scenes with 'PRINT'
Increase transparency by sprinkling PRINT statements, like explaining the scene to the audience:
Wisdom from the almighty MSDN
Microsoft Developer Network (MSDN) is like the Shakespeare of SQL. It tells you that THROW defaults to a user error with severity level 16, and many more secrets.
Was this article helpful?