I\'m trying to switch the current database with a SQL statement. I have tried the following, but all attempts failed:
I have the same problem, I overcame it with an ugly -- but useful -- set of GOTOs.
The reason I call the "script runner" before everything is that I want to hide the complexity and ugly approach from any developer that just wants to work with the actual script. At the same time, I can make sure that the script is run in the two (extensible to three and more) databases in the exact same way.
GOTO ScriptRunner
ScriptExecutes:
--------------------ACTUAL SCRIPT--------------------
-------- Will be executed in DB1 and in DB2 ---------
--TODO: Your script right here
------------------ACTUAL SCRIPT ENDS-----------------
GOTO ScriptReturns
ScriptRunner:
USE DB1
GOTO ScriptExecutes
ScriptReturns:
IF (db_name() = 'DB1')
BEGIN
USE DB2
GOTO ScriptExecutes
END
With this approach you get to keep your variables and SQL Server does not freak out if you happen to go over a DECLARE statement twice.
You can do this:
Declare @dbName nvarchar(max);
SET @dbName = 'TESTDB';
Declare @SQL nvarchar(max);
select @SQL = 'USE ' + @dbName +'; {can put command(s) here}';
EXEC (@SQL);
{but not here!}
This means you can do a recursive select like the following:
Declare @dbName nvarchar(max);
SET @dbName = 'TESTDB';
Declare @SQL nvarchar(max);
SELECT @SQL = 'USE ' + @dbName + '; ' +(Select ... {query here}
For XML Path(''),Type)
.value('text()[1]','nvarchar(max)');
Exec (@SQL)
exec sp_execsql @Sql
The DB change only lasts for the time to complete @sql
http://blog.sqlauthority.com/2007/07/02/sql-server-2005-comparison-sp_executesql-vs-executeexec/
-- If you are using a variable for the database name.
-- Try something like this.
DECLARE @DBName varchar(50)
Set @DBName = 'Database1'; /* could be passed in by a parameter. */
IF( @DBName = 'Database1')
Begin
USE [Database1];
SELECT FROM Table1;
End
IF( @DBName = 'Database2')
Begin
USE [Database2];
SELECT FROM Table2;
End
IF( @DBName is null)
Begin
USE [Database1];
End