title: Stop Script Execution if USE [database] Fails in SQL Server
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>So error checking and try...catch does not work.</p>
  
  <p><strong>Error Check</strong></p>
  
  <pre><code>USE [MYDATABASE]
  
  IF @@ERROR &lt;&gt; 0
  BEGIN
      RAISERROR ('Cannot find database so skipping script creation', 1, 1);
      GOTO AbortScript
  END
  
  ...
  
  AbortScript:
      PRINT 'Aborted!'
  </code></pre>
  
  <p><strong>Try Catch</strong></p>
  
  <pre><code>BEGIN TRY
      USE [MYDATABASE]
      PRINT 'xxxx'
  END TRY
  BEGIN CATCH
  
      PRINT 'OOps Errored'
  
  END CATCH
  </code></pre>
  
  <p>Can you trap these errors?  I am currently using SQL Server 2008 R2.</p>