SQL Server - stop or break execution of a SQL script
Asked Answered
M

22

394

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.

Maggy answered 18/3, 2009 at 17:4 Comment(0)
J
443

The raiserror method

raiserror('Oh no a fatal error', 20, -1) with log

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 LOG option are necessary for it to work this way.

This even works with GO statements, eg.

print 'hi'
go
raiserror('Oh no a fatal error', 20, -1) with log
go
print 'ho'

Will give you the output:

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.

Notice that 'ho' is not printed.

CAVEATS:

  • This only works if you are logged in as admin ('sysadmin' role), and also leaves you with no database connection.
  • If you are NOT logged in as admin, the RAISEERROR() call itself will fail and the script will continue executing.
  • When invoked with sqlcmd.exe, exit code 2745 will be reported.

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 turn noexec off again before any commands will execute.

Example:

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.
Jehad answered 29/4, 2009 at 23:43 Comment(20)
Indeed this is the only method which works with multiple GO statements, which I have to use often in my database update scripts. Thanks!Fay
That's awesome! It's a bit of a "big stick" approach, but there are times when you really need it. Note that it requires both severity 20 (or higher) and "WITH LOG".Bousquet
Note that with noexec method the rest of the script is still interpreted, so you will still get compile-time errors, such as column does not exist. If you want to conditionally deal with known schema changes involving missing columns by skipping over some code, the only way I know to do it is to use :r in sqlcommand mode to reference external files.Giamo
For automatically generated change scripts (VS Database project --> Deploy), NOEXEC is a lifesaverLiquidator
"This will terminate the connection" -- it seems that it doesn't, at least that's what I'm seeing.Frenchpolish
@Frenchpolish are you using severity 20-25? The docs say "Severity levels from 20 through 25 are considered fatal. If a fatal severity level is encountered, the client connection is terminated after receiving the message, and the error is logged in the error and application logs."Jehad
"the client connection is terminated" that's the point -- I want script execution to completely stopFrenchpolish
@Frenchpolish I found your recent question about this. It looks like it's not the raiserror that's the problem. The catch isn't triggering, presumably because the use is interpreted at compile time.Jehad
beware the raise error solution - it seems that some exceptions dont count as proper exceptions - you need to set a certain level of severity (20+) which you may not have permission to do!Martinic
actually turns out the magic number you need for this to work is 11-18, 10 isn't an error/exception really and 18 is the highest number you can reliably setMartinic
I was trying this method and not getting right result when I realized... There is only one E in in raiserror...Malkamalkah
If you want to use this in a script that will be run as a non-sysadmin user, make sure you set severity 18 or lower. The script will continue execution though.Repertory
NoExec On is delightfully elegant If the above comment about syntax/schema validation does not prevent its use in your case. I can't imagine using the raiserror ,20, because it's conditional.Edyth
I have no control over user rights, and my admin thinks he gave enough admin rights ( on an azure database). Still, SQL Server denies me the ability to use >18 severity + with log (I am no sysadmin). The version with SQLCMD :on error exit is working fine, though : https://mcmap.net/q/86652/-sql-server-stop-or-break-execution-of-a-sql-scriptKalamazoo
I can confirm that on my local version of SQL 2017 Developer Edition that raiserror('Oh no a fatal error', 20, -1) with log does indeed terminate the connection (which is appropriate and helpful in my use case).Swifter
Note that the sql file is still parsed, and any errors with missing columns will give errors. You can use parseonly to stop the parsing of the script. This will work the same way as noexec.Skintight
I do not understand. I followed the instructions. I entered the following SQL after each GO. IF (XACT_STATE()) <> 1 BEGIN Set NOCOUNT OFF ;THROW 525600, 'Rolling back transaction.', 1 ROLLBACK TRANSACTION; set noexec on END; But the execution never stopped, and I ended up with three "Rolling back Transaction"s errors raised. Any ideas?Smock
I got "Only System Administrator can specify WITH LOG option for RAISERROR command"... :-(Obsequent
The command set noexec on is perfect for debugging! using raiserror always drives me nuts because my script always seems to stop BEFORE processing the lines right above the raiserror command. noexec does not have this issue.Aziza
While this works great from SSMS, is does not seem to work inside IF blocks within Agent. I get an Incorrect syntax near the keyword 'end' message.Pontic
P
216

Just use a RETURN (it will work both inside and outside a stored procedure).

Picnic answered 18/3, 2009 at 17:23 Comment(8)
For some reason, I was thinking that return didn't work in scripts, but I just tried it, and it does! ThanksMaggy
In a script, you can't do a RETURN with a value like you can in a stored procedure, but you can do a RETURN.Bousquet
No it only terminates until the next GO The next batch (after GO) will run as usualAxes
But you can SET CONTEXT_INFO at the end of a batch and check if it is what is expected at the start of the next batch as described in jaraics response.Dorie
dangerous to assume as it will continue after then next GO.Sumatra
GO is a script terminator or delimiter; it's not SQL code. GO is just an instruction to the client you're using to send command to the database engine that a new script is starting after the GO delimiter.Ostium
This is an older question but still relevant. Using RETURN with an IF/ELSE statement also allows some user info or logging to take place: IF (SELECT @@SERVERNAME) LIKE '%WrongServerName%' BEGIN SELECT 'Please find someone else to help you with this' AS Cmon_Man RETURN END ELSE SELECT 'Continuing on...' AS Very_GoodColeen
This answer doesn't help with the question at all, which is "Is there a way to immediately stop execution of a SQL script".Collin
P
63

If you can use SQLCMD mode, then the incantation

:on error exit

(INCLUDING the colon) will cause RAISERROR to actually stop the script. E.g.,

:on error exit

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SOMETABLE]') AND type in (N'U')) 
    RaisError ('This is not a Valid Instance Database', 15, 10)
GO

print 'Keep Working'

will output:

Msg 50000, Level 15, State 10, Line 3
This is not a Valid Instance Database
** An error was encountered during execution of batch. Exiting.

and the batch will stop. If SQLCMD mode isn't turned on, you'll get parse error about the colon. Unfortuantely, it's not completely bulletproof as if the script is run without being in SQLCMD mode, SQL Managment Studio breezes right past even parse time errors! Still, if you're running them from the command line, this is fine.

Protasis answered 7/4, 2010 at 6:13 Comment(4)
Great comment, thanks. I'll add that in SSMS SQLCmd mode is toggle under the Query menu.Maureen
this is useful - means you dont need the -b option when runningMartinic
then the incantation... but how do I cast Magic Missle?!Hyperborean
perfect. does not require sysadmin ultra extra user rightsKalamazoo
L
25

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:

declare @valid bit

set @valid = 1

if -- Condition(s)
begin
  print 'Condition(s) failed.'
  set @valid = 0
end

-- Additional validation with similar structure

-- Final check that validation passed
if @valid = 1
begin
  print 'Validation succeeded.'

  -- Do work
end

Even if your validation is more complex, you should only need a few flag variables to include in your final check(s).

Leena answered 18/3, 2009 at 17:7 Comment(5)
Yeah, I'm using IFs in other parts of the script, but I don't want to have to check every local variable before I try to do an insert. I'd rather just have the whole script stop, and force the user to check the inputs. (This is just a quick and dirty script)Maggy
I'm not quite sure why this answer has been marked down becuase it is technically correct, just not what the poster "wants" to do.Statecraft
Is it possible to have multiple blocks within Begin..End? Meaning STATEMENT; GO; STATEMENT; GO; etc etc? I'm getting errors and I guess that might be the reason.Inly
This is far more reliable than RAISERROR, especially if you don't know who is going to be running the scripts and with what privileges.Dichasium
@John Sansom: The only problem I see here is that the IF statement does not work if you are attempting to branch over a GO statement. This is a big problem if your scripts rely on the GO statements (e.g. DDL statements). Here is an example that works without the first go statement: declare @i int = 0; if @i=0 begin select '1st stmt in IF block' go end else begin select 'ELSE here' end goGlossography
P
18

In SQL 2012+, you can use THROW.

THROW 51000, 'Stopping execution because validation failed.', 0;
PRINT 'Still Executing'; -- This doesn't execute with THROW

From MSDN:

Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct ... If a TRY…CATCH construct is not available, the session is ended. The line number and procedure where the exception is raised are set. The severity is set to 16.

Pelvis answered 19/11, 2015 at 16:21 Comment(3)
THROW is meant to replace RAISERROR, but you can't prevent subsequent batches in the same script file with it.Chyou
Correct @NReilingh. That's where Blorgbeard's answer is really the only solution. It does require sysadmin, though (severity level 20), and it is fairly heavy-handed if there aren't multiple batches in the script.Pelvis
set xact abort on if you want to cancel the current transcation as well.Natterjack
S
17

You can alter the flow of execution using GOTO statements:

IF @ValidationResult = 0
BEGIN
    PRINT 'Validation fault.'
    GOTO EndScript
END

/* our code */

EndScript:
Sholom answered 9/12, 2016 at 15:21 Comment(3)
using goto is an acceptable way to handle exception. Reduces the amount of variables and nesting and does not cause a disconnect. It's probably preferable to the archaic exception handling that SQL Server scripting allows.Findley
Just like ALL of the other suggestions here, this doesn't work if "our code" contains a "GO" statement.Greatgrandaunt
Oddly, this still parsed the script; I got "Incorrect syntax near the keyword 'with'" errors but I was able to prevent the script from running without sysadmin (after removing all the 'GO' commands). Thanks.Obsequent
K
14

I extended the noexec on/off solution successfully with a transaction to run the script in an all or nothing manner.

set noexec off

begin transaction
go

<First batch, do something here>
go
if @@error != 0 set noexec on;

<Second batch, do something here>
go
if @@error != 0 set noexec on;

<... etc>

declare @finished bit;
set @finished = 1;

SET noexec off;

IF @finished = 1
BEGIN
    PRINT 'Committing changes'
    COMMIT TRANSACTION
END
ELSE
BEGIN
    PRINT 'Errors occured. Rolling back changes'
    ROLLBACK TRANSACTION
END

Apparently the compiler "understands" the @finished variable in the IF, even if there was an error and the execution was disabled. However, the value is set to 1 only if the execution was not disabled. Hence I can nicely commit or rollback the transaction accordingly.

Karlin answered 25/10, 2011 at 12:27 Comment(1)
I do not understand. I followed the instructions. I entered the following SQL after each GO. IF (XACT_STATE()) <> 1 BEGIN Set NOCOUNT OFF ;THROW 525600, 'Rolling back transaction.', 1 ROLLBACK TRANSACTION; set noexec on END; But the execution never stopped, and I ended up with three "Rolling back Transaction"s errors raised. Any ideas?Smock
S
13

you could wrap your SQL statement in a WHILE loop and use BREAK if needed

WHILE 1 = 1
BEGIN
   -- Do work here
   -- If you need to stop execution then use a BREAK


    BREAK; --Make sure to have this break at the end to prevent infinite loop
END
Saucedo answered 18/3, 2009 at 17:27 Comment(4)
I kind of like the looks of this, it seems a little nicer than raise error. Definitely don't want to forget the break at the end!Maggy
You could also use a variable and immediately set it at the top of the loop to avoid the "split". DECLARE @ST INT; SET @ST = 1; WHILE @ST = 1; BEGIN; SET @ST = 0; ...; END More verbose, but heck, it's TSQL anyway ;-)Sweeny
This is how some people perform goto, but it is more confusing to follow than goto.Natterjack
This approach protects from an unexpected occasional GO. Appreciative.Malpractice
K
12

Further refinig Sglasses method, the above lines force the use of SQLCMD mode, and either treminates the scirpt if not using SQLCMD mode or uses :on error exit to exit on any error
CONTEXT_INFO is used to keep track of the state.

SET CONTEXT_INFO  0x1 --Just to make sure everything's ok
GO 
--treminate the script on any error. (Requires SQLCMD mode)
:on error exit 
--If not in SQLCMD mode the above line will generate an error, so the next line won't hit
SET CONTEXT_INFO 0x2
GO
--make sure to use SQLCMD mode ( :on error needs that)
IF CONTEXT_INFO()<>0x2 
BEGIN
    SELECT CONTEXT_INFO()
    SELECT 'This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!'
    RAISERROR('This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!',16,1) WITH NOWAIT 
    WAITFOR DELAY '02:00'; --wait for the user to read the message, and terminate the script manually
END
GO

----------------------------------------------------------------------------------
----THE ACTUAL SCRIPT BEGINS HERE-------------
Khichabia answered 18/3, 2009 at 17:4 Comment(2)
This is the only way I found to work around the SSMS lunacy of being unable to abort the script. But I added 'SET NOEXEC OFF' at the beginning, and 'SET NOEXEC ON' if not in SQLCMD mode, otherwise the actual script will keep going unless you raise an error at level 20 with log.Heaviness
!!!!!!!!!!!!! THANK YOU !!!!!!!!!!!! Most answers I have seen disregard script with multiple batches. And they ignore dual usage in SSMS and SQLCMD. My script is fully runable in SSMS -- but I want an F5 prevention so they don't remove an existing set of objects on accident. SET PARSEONLY ON worked well enough for that. But then you can't run with SQLCMD. I have also not seen remarks about SET NOCOUNT ON not working when anything in the same batch doesn't compile -- that through me sideways for a while. I added a tiny bit to this in an answer below.Wivestad
T
10

I use RETURN here all the time, works in script or Stored Procedure

Make sure you ROLLBACK the transaction if you are in one, otherwise RETURN immediately will result in an open uncommitted transaction

Tackett answered 18/3, 2009 at 18:28 Comment(2)
Doesn't work with a script containing multiple batches (GO statements) - see my answer for how to do that.Jehad
RETURN just exits the current block of statements. If you are in an IF END block, execution will continue after the END. This means you cannot use RETURN to end execution after testing for some condition, because you will always be in IF END block.Patronymic
N
8

Is this a stored procedure? If so, I think you could just do a Return, such as "Return NULL";

Nichani answered 18/3, 2009 at 17:7 Comment(2)
Thanks for the answer, that's good to know, but in this case it's not a stored proc, just a script fileMaggy
@Gordon Not always (here I am searching). See other answers (GO trips it up, for one thing)Heaviness
S
7

Wrap your appropriate code block in a try catch block. You can then use the Raiserror event with a severity of 11 in order to break to the catch block if you wish. If you just want to raiserrors but continue execution within the try block then use a lower severity.

TRY...CATCH (Transact-SQL)

Statecraft answered 18/3, 2009 at 17:18 Comment(4)
I've never seen a try-catch in SQL - would you mind posting a quick example of what you mean?Maggy
it's new to 2005. BEGIN TRY { sql_statement | statement_block } END TRY BEGIN CATCH { sql_statement | statement_block } END CATCH [ ; ]Cassaba
@Andy: Reference added, example included.Statecraft
TRY-CATCH block doesn't allow GO inside itelf.Bodoni
B
6

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:

-- =================================
PRINT 'Start Test 1 - RAISERROR'

IF 1 = 1 BEGIN
    RAISERROR('Error 1, level 11', 11, 1)
    RETURN
END

IF 1 = 1 BEGIN
    RAISERROR('Error 2, level 11', 11, 1)
    RETURN
END
GO

PRINT 'Test 1 - After GO'
GO

-- =================================
PRINT 'Start Test 2 - Try/Catch'

BEGIN TRY
    SELECT (1 / 0) AS CauseError
END TRY
BEGIN CATCH
    SELECT ERROR_MESSAGE() AS ErrorMessage
    RAISERROR('Error in TRY, level 11', 11, 1)
    RETURN
END CATCH
GO

PRINT 'Test 2 - After GO'
GO

Results:

Start Test 1 - RAISERROR
Msg 50000, Level 11, State 1, Line 5
Error 1, level 11
Test 1 - After GO
Start Test 2 - Try/Catch
 CauseError
-----------

ErrorMessage
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Divide by zero error encountered.

Msg 50000, Level 11, State 1, Line 10
Error in TRY, level 11
Test 2 - After GO

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 like IF @error <> 0 BEGIN ....)

Bousquet answered 18/3, 2009 at 21:10 Comment(2)
Can't do that with CREATE PROCEDURE etc. See my answer for a solution.Jehad
Blogbeard's solution is great. I've been working with SQL Server for years and this is the first time I've seen this.Bousquet
O
3

you can use RAISERROR.

Officinal answered 18/3, 2009 at 17:5 Comment(3)
This makes no sense to me- raising an avoidable error (assuming we're talking about referential validation here) is a horrible way to do this if validation is possible before the inserts take place.Leena
raiserror can be used as an informational message with a low severity setting.Officinal
The script will continue unless certain conditions stated in the accepted answer are met.Firecrest
R
3

This was my solution:

...

BEGIN
    raiserror('Invalid database', 15, 10)
    rollback transaction
    return
END
Rotenone answered 27/6, 2012 at 8:40 Comment(0)
B
3

You can use GOTO statement. Try this. This is use full for you.

WHILE(@N <= @Count)
BEGIN
    GOTO FinalStateMent;
END

FinalStatement:
     Select @CoumnName from TableName
Bless answered 7/9, 2015 at 6:58 Comment(1)
GOTO is supposed to be a bad coding practice, use of "TRY..CATCH" is recommended, as it was introduced since SQL Server 2008, followed by THROW in 2012.Thrust
E
1

Thx for the answer!

raiserror() works fine but you shouldn't forget the return 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.

Exude answered 31/3, 2009 at 13:52 Comment(0)
G
1

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.

Gilmagilman answered 5/7, 2012 at 7:34 Comment(1)
What does your answer adds to the accepted answer with 60+ upvotes? Have you read it? Check this metaSO question and Jon Skeet: Coding Blog on how to give a correct answer.Baden
T
1

Enclose it in a try catch block, then the execution will be transfered to catch.

BEGIN TRY
    PRINT 'This will be printed'
    RAISERROR ('Custom Exception', 16, 1);
    PRINT 'This will not be printed'
END TRY
BEGIN CATCH
    PRINT 'This will be printed 2nd'
END CATCH;
Tomahawk answered 28/5, 2020 at 11:34 Comment(0)
W
1

Many thanks to all the other people here and other posts I have read. But nothing was meeting all of my needs until @jaraics answered.

Most answers I have seen disregard scripts with multiple batches. And they ignore dual usage in SSMS and SQLCMD. My script is fully runable in SSMS -- but I want F5 prevention so they don't remove an existing set of objects on accident.

SET PARSEONLY ON worked well enough to prevent unwanted F5. But then you can't run with SQLCMD.

Another thing that slowed me down for a while is how a Batch will skip any further commands when there is an error - so my SET NOCOUNT ON was being skipped and thus the script still ran.

Anyway, I modified jaraics' answer just a bit: (in this case, I also need a database to be active from commandline)

-----------------------------------------------------------------------
-- Prevent accidental F5
-- Options:
--     1) Highlight everything below here to run
--     2) Disable this safety guard
--     3) or use SQLCMD
-----------------------------------------------------------------------
set NOEXEC OFF                             -- Reset in case it got stuck ON
set CONTEXT_INFO  0x1                      -- A 'variable' that can pass batch boundaries
GO                                         -- important !
if $(SQLCMDDBNAME) is not null
    set CONTEXT_INFO 0x2                   -- If above line worked, we're in SQLCMD mode
GO                                         -- important !
if CONTEXT_INFO()<>0x2 
begin
    select 'F5 Pressed accidentally.'
    SET NOEXEC ON                          -- skip rest of script
END
GO                                         -- important !
-----------------------------------------------------------------------

< rest of script . . . . . >


GO
SET NOEXEC OFF
print 'DONE'
Wivestad answered 28/4, 2021 at 23:1 Comment(0)
E
1

I have been using the following script and you can see more details in my answer here.

RAISERROR ( 'Wrong Server!!!',18,1) WITH NOWAIT RETURN
    
    print 'here'
    
    select [was this executed]='Yes'

--but sometimes you cannot use RETURN, then I use set noexec on just like in the example below:

SET NOEXEC OFF;
IF @@SERVERNAME NOT IN ('serverSQL0003U0', 'serverSQL0004U0')
  BEGIN;

   RAISERROR('Wrong Server!Should be on serverSQL0003U0 or serverSQL0004U0',16,1)
    SET NOEXEC ON;

  END;
Eyde answered 20/7, 2022 at 16:52 Comment(0)
M
0

Back in the day we used the following...worked best:

RAISERROR ('Error! Connection dead', 20, 127) WITH LOG
Mcmurray answered 3/1, 2019 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.