Explain Codes LogoExplain Codes Logo

T-sql STOP or ABORT command in SQL Server

sql
error-handling
script-execution
sql-server
Nikita BarsukovbyNikita Barsukov·Dec 14, 2024
TLDR

To abort execution in T-SQL, use the RAISERROR function with a severity of 20 or higher, which enforces a session disconnection:

RAISERROR('Execution is about to get terminated', 20, 1) WITH LOG;

Take note, this approach will immediately terminate the session and perform a rollback operation on the ongoing transaction.

Halting execution: Various approaches

Immediate exit with RAISEERROR

Putting a STOP to your script? RAISERROR is your red card:

-- "You shall not pass!" RAISERROR ('STOP! Hammertime.', 11 ,1);

This technique stops execution and fires a message. Severity levels from 0 through 18 can be specified by any user.

Loop interruption with GOTO

For conditional halting, use the GOTO statement. Make it take a leap!

IF @YourCondition = 'Bad' GOTO StopExecution -- Some script here StopExecution:

This is your halt-at-will magic button to control your T-SQL's destiny.

Conditional execution using variables

Control freaks, rejoice! Use control variables and Rule the Algo World!

DECLARE @ShouldRunScript BIT = 0; -- Toggle to control execution IF @ShouldRunScript = 0 RETURN -- Execution skipped, the boss said no -- Valuable code is here

Script deactivation: The sleeper modes

The art of tactical sleeping: SET NOEXEC

A sleeper command for your all-nighter codes:

SET NOEXEC ON; -- Time for script hibernation -- Beauty sleep here SET NOEXEC OFF; -- The awakening

Here the script just rests a while, checks its syntax and then doesn't run unless you say so!

Disarm with IF condition

To disarm active scripts, the IF 0=1... technique can be a lifesaver:

IF 0=1 BEGIN -- Your Script here, but it's chilling END

This is like the "play dead" tactic for your script.

Silent bye with RETURN

When you need the script to quietly exit, stage left:

-- The silent exit, put on your invisibility cloak RETURN -- Remaining script here doesn't get any attention

This is your quiet goodbye, the Irish Exit of SQL.

Script error handling: RAISERROR in action

Spitting out custom messages with RAISERROR

Be dramatic! Throw custom alerts and warnings:

RAISERROR('Talk to the hand, script is inactive.', 10, 1);

This nifty trick keeps your script execution status flashy and lively.

Usage fine prints: RAISERROR

When using RAISERROR in severity level 20, be careful as the sysadmin privilege is a prerequisite. Consult MSDN documentation for understanding the error logging procedure precisely.