<\/script>')

The statement "USE @dbname" does not work, why? How to do it?

I have this t-sql fragment:

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 a variable (the third line of the fragment) does not work. Why is this not working?

+4
source share
4 answers

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

+8
source

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

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

I hope someone else can do better :-)

+4
source

SQL Server does not accept a USE statement with a variable.

To use database names dynamically, you need 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 with sp_SQLExec

+3
source

How do I do this with an if statement:

 if @DBName = 'DB1' <query with DB1> else <query with DB2> 
+1
source

Source: https://habr.com/ru/post/1300057/


All Articles