2

Typically in a SQL Server script I will have a USE [database] statement at the start. This would be for a Schema Table creation script for example.

The script is assuming that the database already exists. However, to prevent accidentally running the script against a master database, I just want the script to terminate execution.

So error checking and try...catch does not work.

Error Check

USE [MYDATABASE]

IF @@ERROR <> 0
BEGIN
    RAISERROR ('Cannot find database so skipping script creation', 1, 1);
    GOTO AbortScript
END

...

AbortScript:
    PRINT 'Aborted!'

Try Catch

BEGIN TRY
    USE [MYDATABASE]
    PRINT 'xxxx'
END TRY
BEGIN CATCH

    PRINT 'OOps Errored'

END CATCH

Can you trap these errors? I am currently using SQL Server 2008 R2.

2 Answers 2

1

Check if the database exists first:

IF (NOT EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = 'mydatabase')) 
BEGIN
    RAISERROR ('Cannot find database so skipping script creation', 1, 1);
    GOTO AbortScript
END;

USE [MYDATABASE]
Sign up to request clarification or add additional context in comments.

Comments

0

I've been trying to abort a large SQL script that includes many batches (marked with "GO"). Unfortunately you can't use a GOTO block, IF block, or TRY-CATCH to skip multiple batches, but you can turn off command execution, which has the same effect.

IF EXISTS (SELECT 1 FROM sys.tables WHERE name = 'MyTable')
     SET NOEXEC ON

(Don't forget to SET NOEXEC OFF at the end of your script)

Detailed reference here.

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.