Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 511
NitroxDM Avatar asked Dec 29 '22 22:12

NitroxDM


1 Answers

Unfortunately, no.

Unless you can 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 statement, but will not leave a lasting effect on the scope you execute the execute statement from.

In other words, this:

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

Will not set the current database permanently, but if you altered the above code like this:

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

Then the result of those two queries will be different (assuming you're not in SweetDB already), since the first select, executed inside execute is executing in SweetDB, but the second isn't.

like image 98
Lasse V. Karlsen Avatar answered Jan 13 '23 18:01

Lasse V. Karlsen