I have a script that I'm working on that uses a variable referencing the
database name (@DBName). When I try to use this in the form of "USE
@DBName", it doesn't work. If I use an nvarchar datatype and create a
string (like the following);
DECLARE @SQL nvarchar(2000)
DECLARE @DBName nvarchar(200)
SET @SQL = 'USE ' + @DBName
EXEC sp_sqlexec @SQL
The script runs, but the script remains focused on the master.
Is there any way to specify USE with a variable?