Is there a way to select a database from a variable?

Is there a way to select a database from a variable?

Declare @bob as varchar(50); Set @bob = 'SweetDB'; GO USE @bob 
+4
sql sql-server dynamic-sql
Jun 01 '09 at 23:16
source share
3 answers

Unfortunately not.

If you cannot execute the rest of your batch as dynamic SQL.

Using execute to dynamically execute SQL will change the context for the scope of the execute , but it will not leave a lasting effect on the scope of the execute .

In other words, it is:

 DECLARE @db VARCHAR(100) SET @db = 'SweetDB' EXECUTE('use ' + @db) 

Will not install the current database forever, but if you changed the above code as follows:

 DECLARE @db VARCHAR(100) SET @db = 'SweetDB' EXECUTE('use ' + @db + ';select * from sysobjects') select * from sysobjects 

Then the result of these two queries will be different (if you are not already in SweetDB), since the first choice made inside execute is executed in SweetDB, and the second one is not.

+9
Jun 01 '09 at 23:36
source share
 declare @NewDB varchar(50) set @NewDB = 'NewDB' execute('use ' + @NewDB) 
0
Jun 01 '09 at 23:23
source share

#TempTables will be submitted via GO

you can create a table in the first batch, insert / select data as necessary in this or any subsequent batch.

Here is an example syntax:

 CREATE TABLE #YourTableName ( col1 int not null primary key identity(1,1) ,col2 varchar(10) ) 
0
Jun 2 '09 at 13:02
source share



All Articles