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 USE myDatabaseName
.
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 [master]
database.
I tried the following but doesn't seem to work as it keeps applying the rest of the create tables
codes to [master]
.
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
new query
at the server level.