views:

289

answers:

4

I've got this t-sql snippet:

DECLARE @db_name varchar(255);
SET @db_name = 'MY_DATABASE'; -- assuming there is database called 'my_database'
USE @db_name -- this line ends with error "Incorrect syntax near '@db'."

But USE with variable (third line of snippet) doesn't work. Why it doesn't work?

+6  A: 

You cannot provide the name of the database for USE statement in a variable.

Quassnoi
@Quassnoi: Why not? and is there a walk-around?
Sung Meister
+2  A: 

SQL Server will not accept the USE statement with a variable.

To use database names dynamically, you have to create dynamic SQL statements with (almost) fully qualified names as follows:

Declare @SQL VarChar (100)

SET @SQL = 'SELECT * FROM ' + @DatabaseName + '.dbo.TableName'

and then you execute it using sp_SQLExec

Raj More
Just beware of SQL injection as I commented on Jørn's answer.
Aaron Bertrand
+2  A: 

As you have noticed, the USE statement does not accept a variable as parameter. The only alternative that quickly comes to mind is quite crude and extremely error prone, but here you go:

EXEC ('USE ' + @db_name + '
       SELECT * FROM some_table
       INSERT INTO some_table VALUES (1)')

I hope that someone else can do better :-)

Jørn Schou-Rode
Also quite prone to SQL injection. Look that up (as well as the QUOTENAME() function, which can help in a lot cases).
Aaron Bertrand
Indeed it is. Depending on the use case, this might or might not be a problem :)
Jørn Schou-Rode
A: 

Man Awesome! You saved my life!

thanks a lot Jørn Schou-Rode!!!!!

rjmalo