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)
If SQLCMD mode is an option for your (within SSMS, for example), you can do this:
Or, your original syntax was pretty close. Try this: