3

The following is not working and I am definitely missing the obvious but would be nice if somebody could explain why is not working. I need to change db dynamically.

The print out looks good but does not change db in the SQL Server drop down.

DECLARE @tempSql nvarchar(4000);
DECLARE @FinalSQL nvarchar(4000);
DECLARE @dbName varchar(100);

SET @dbName = 'Pubs';
SET @tempSql = 'SELECT DB_NAME()';

SET @FinalSQL = 'USE ' + @dbName + '; EXEC sp_executesql N''' + @tempSql + '''';
EXEC (@FinalSQL)
1
  • Is SQLCMD mode an option for you? Commented Oct 29, 2011 at 6:59

3 Answers 3

2

If SQLCMD mode is an option for your (within SSMS, for example), you can do this:

:setvar dbname Pubs
USE [$(dbname)]
SELECT DB_NAME()

Or, your original syntax was pretty close. Try this:

DECLARE @db AS NVARCHAR(258);
SET @db = QUOTENAME(N'Pubs');
EXEC(N'USE ' + @db + N'; EXEC(''SELECT DB_NAME();'');');
GO
Sign up to request clarification or add additional context in comments.

3 Comments

I will look into sqlcmd.Which makes me think that there is no way todo in dynamic sql then
@user231465 - It does work but it gets reset as soon as the dynamic SQL batch exits so you would need to either call the code to execute from within the dynamic SQL itself or put the code inline there.
@MartinSmith it does work.Could you explain what you mean by "put the code inline there"
1

There is a way to access data from a specific database by using this syntax :

FROM DatabaseName..TableName

maybe you should use a dynamic database name in your scripts, then change it whenever you need

otherwise, take a look at this : http://www.sqlteam.com/article/selecting-data-from-different-databases

Comments

1

Executing the dynamic SQL is done in a scope of its own.

So you do change the current database, as you see, but only within the scope of the dynamic SQL.

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.