Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: Terminate SQL From Running

Is there away to cause a script to prevent running if an if statement is true even with "GO"'s?

For example I want to do something similar to the following:

insert into table1 (col1, col2) value ('1', '2')
GO
if exists(select * from table1 where col1 = '1')
  BEGIN
    --Cause Script to fail
  END
GO
insert into table1 (col1, col2) value ('1', '2') --Wont run

The actual purpose of doing this is to prevent table create scripts/inserts/deletes/updates from running more than once when we drop of packages for the DBA's to run.

like image 772
Nic Avatar asked Nov 26 '25 22:11

Nic


2 Answers

GO is not a transact-sql keyword - it's actually a batch terminator understood by common SQL Server tools. If you use it in your application, your app wil fail.

Why wouldn't you do something like this?

IF NOT EXISTS (select * from table1 where col1 = '1')
BEGIN
     --Do Some Stuff
END

Rather than abort the script if the condition is met, only run the script if the condition isn't met.

Alternatively, you could wrap the code in a proc and use RETURN to exit from the proc.

like image 115
Aaron Alton Avatar answered Nov 29 '25 13:11

Aaron Alton


According to the documentation, certain values passed for the severity to RAISEERROR() can cause varying levels of termination.

The ones of most interest (if you are running a script through SQL Management Studio or similar, and want to prevent any attempt to run any subsequent commands in a the file) may be:

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.

like image 32
Jason Musgrove Avatar answered Nov 29 '25 11:11

Jason Musgrove



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!