1

I would like to know how I can switch from one database to another within the same script. I have a script that reads the header information from a SQL Server .BAK file and loads the information into a test database. Once the information is in the temp table (Test database) I run the following script to get the database name.

This part works fine.

INSERT INTO @HeaderInfo EXEC('RESTORE HEADERONLY 
FROM DISK = N''I:\TEST\database.bak''
WITH NOUNLOAD')

DECLARE @databasename varchar(128);
SET @databasename = (SELECT DatabaseName FROM @HeaderInfo);

The problem is when I try to run the following script nothing happens. The new database is never selected and the script is still on the test database.

EXEC ('USE '+ @databasename)

The goal is switch to the new database (USE NewDatabase) so that the other part of my script (DBCC CHECKDB) can run. This script checks the integrity of the database and saves the results to a temp table.

What am I doing wrong?

2 Answers 2

1

You can't expect a use statement to work in this fashion using dynamic SQL. Dynamic SQL is run in its own context, so as soon as it has executed, you're back to your original context. This means that you'd have to include your SQL statements in the same dynamic SQL execution, such as:

declare @db sysname = 'tempdb';
exec ('use ' + @db + '; dbcc checkdb;')

You can alternatively use fully qualified names for your DB objects and specify the database name in your dbcc command, even with a variable, as in:

declare @db sysname = 'tempdb';
dbcc checkdb (@db);
Sign up to request clarification or add additional context in comments.

1 Comment

@user36578 you can always accept an answer if it worked to let future visitors know of the outcome.
0

You can't do this because Exec scope is limited to dynamic query. When exec ends context is returned to original state. But context changes in Exec itself. So you should do your thing in one big dynamic statement like:

DECLARE @str NVARCHAR(MAX)

SET @str = 'select * from table1
USE DatabaseName
select * from table2'

EXEC (@str)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.