title: SQL Server: Change current database via variable
body: <p>I'm using SQL Server 2008 and am trying to change the current database name to one in a variable. I normally do this explicitly with the statment <code>USE myDatabaseName</code>.
  The question arises because if I am running a script and if I don't change the database name it creates all the tables in the <code>[master]</code> database.</p>
  
  <p>I tried the following but doesn't seem to work as it keeps applying the rest of the <code>create tables</code> codes to <code>[master]</code>.</p>
  
  <pre><code>DECLARE @dbName CHAR(50)
  DECLARE @SqlQuery varchar(50)
  SET @dbName = 'MyNewDatabaseName'
  
  IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = @dbName)
  BEGIN
      SELECT @SqlQuery = 'CREATE DATABASE ' + @dbName + 'COLLATE SQL_Latin1_General_CP1_CI_AS'
      EXEC(@SqlQuery) 
  END
  
  Select @SqlQuery = 'Use ' + @dbName
  EXEC(@SqlQuery)
  go
  </code></pre>