6

I have a huge SQL script with many batches (using GO).

On certain conditions, I want to stop the whole execution of this script.

I tried using NOEXEC, but I keep on getting invalid object errors, since my script includes creating and adding data to new tables and columns.

I do not want to use RAISERROR, is there any other way to do this?

3
  • I don't know of a way of doing this. Are the GO statements necessary? I'd look to either make it a single batch and break out of that or find some way of executing these batches individualls (e.g. Powershell or other scripting language, SSIS, put them into stored procedures etc). Commented Sep 24, 2015 at 13:59
  • How are you executing this script? Management Studio? SQLCMD? Application? Commented Sep 24, 2015 at 14:04
  • I am executing it in management studio Commented Sep 24, 2015 at 14:08

2 Answers 2

4

There are no good solutions to this problem. One way you can share data between batches is tables(persistent or temporary). So you can have some logic that depends on some state of that table or value of particular columns in that table like this:

--CREATE TABLE debug(col int)
--INSERT INTO debug VALUES(1)
--DELETE FROM debug


SELECT 1
GO

SELECT 2

SELECT 3

GO

IF EXISTS(SELECT * FROM debug)
    SELECT 6

GO

Just add IF EXISTS(SELECT * FROM debug) this line to every place in script that you want to skip and depending on the fact that the table has some rows or not those code blocks will execute or not.

Sign up to request clarification or add additional context in comments.

2 Comments

Seems like a good solution, but it won't make sense in my situation since I have a huge script and its not advisable to add check before every batch.
@RandomUser, you just have no alternative.
0

just use SET NOEXEC ON when you want to stop execution.

 Go
 Select 'I want to kill the job after some error or based on some validation.
 Go
 Select 'Raiserror not working'
  Go
 Select 'I have to be admin to define severity 20'
 go
Select 'I got an error, come custom validation failed, I don't want to run the 
 rest  of the script'.
Go
 SET NOEXEC ON
 Select 'rest of the script should not run after NOEXEC on executed'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.