title: In SQL server is there any way to get the 'use database' command to accept a variable
body: <p>I would like to write a 'generic' script to operate on a number of databases. The 'use databasename' commands will be distributed in the body of the script. I would rather show the database name information at the top of the script. So ideally:</p>
  
  <pre>
  declare @db varchar(100)
  set @db = 'data_in'
  use @db
  </pre>
  
  <p>This fails. So perhaps</p>
  
  <pre>
  declare @db varchar(100)
  set @db = 'data_in'
  exec ('use '+@db)
  </pre>
  
  <p>This executes, but presumably changes the database only in the context of the query in the string. <br>
  So is there any other way without placing the whole script into a string and executing it that way ie. a cure worse than the disease?</p>