title: How to use T-SQL to call exec(@sql) to change current database?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/969046/in-sql-server-is-there-any-way-to-get-the-use-database-command-to-accept-a-var">In SQL server is there any way to get the &#39;use database&#39; command to accept a variable</a>  </p>
  </blockquote>
  
  
  
  <p>We can change the database by their name is no problem as below</p>
  
  <pre><code>USE master
  GO
  </code></pre>
  
  <p>But I need this in a script and have the database name in a variable. How to make this?</p>
  
  <pre><code>select @cmd = N'use ' + @oldDb  + N';'
  exec sp_executesql @cmd
  </code></pre>
  
  <p>That doesn't work - the current database stays the same after the execution.</p>
  
  <p>Is something possible at all?</p>