title: Why I cannot change database dynamically SQL Server 2008
body: <p>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.</p>
  
  <p>The print out looks good but does not change db in the SQL Server drop down.</p>
  
  <pre><code>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)
  </code></pre>