Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: Change current database via variable

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
like image 275
Rick Avatar asked Feb 06 '12 18:02

Rick


People also ask

How do I change the current database in SQL?

In Azure SQL Database, the database parameter can only refer to the current database. If a database other than the current database is provided, the USE statement does not switch between databases, and error code 40508 is returned. To change databases, you must directly connect to the database.

How do I change the context of a database?

Try using sp_MSforeachdb (be aware, it is undocumented). Put either of these in your loop against the db names and this should solve your problem. Put either of these in your loop against the db names and this should solve your problem." You could use xp_execresultset to set database context, e.g.

How can use dynamic database in SQL Server?

Syntax for dynamic SQL is to make it string as below : 'SELECT statement'; To run a dynamic SQL statement, run the stored procedure sp_executesql as shown below : EXEC sp_executesql N'SELECT statement';

What is @@ variable in SQL?

In SQL Server, symbol @@ is prefixed to global variables. The server maintains all the global variables.


2 Answers

Executing USE some_db in dynamic SQL does work but unfortunately when the scope exits the database context gets changed back to what it was originally.

You can use sqlcmd mode for this (enable this on the "Query" menu in Management Studio).

:setvar dbname "MyNewDatabaseName" 

IF DB_ID('$(dbname)') IS NULL
    BEGIN

    DECLARE @SqlQuery NVARCHAR(1000);
    SET @SqlQuery = N'CREATE DATABASE ' + QUOTENAME('$(dbname)') + ' 
            COLLATE SQL_Latin1_General_CP1_CI_AS'
    EXEC(@SqlQuery) 

    END

GO

USE $(dbname)

GO
like image 135
Martin Smith Avatar answered Sep 24 '22 03:09

Martin Smith


Just to add Martin Smith's answer,

If this is so you can deploy your Table creation or Table modification to multiple database you can separate your Database Creation and Object creation scripts, and then run them in sequence using a bat file using the input file -i. This enables you to change databases between scripts from master to the new database.

then your batch file might

 sqlcmd -S server\Instance -E -i createdatabase.sql 
 sqlcmd -S server\Instance -E -d MyNewDatabaseName -i CreateTables.sql 

Typically however I've only needed to do this when I was deploying changes to multiple databases (don't ask why) e.g.

 sqlcmd -S server\Instance -E -d OneDatabase -i CreateTables.sql 
 sqlcmd -S server\Instance -E -d AnotherDatabase -i CreateTables.sql 
like image 45
Conrad Frix Avatar answered Sep 22 '22 03:09

Conrad Frix