title: How to Select from a database using a dynamic variable
body: <p>I have a SQL 2008 database that is stored on the same instance, but this database is created by the user and name is stored in SQL table. How do I write a select statement using dynamic sql or is there a another way</p>
  
  <p>So for example:</p>
  
  <p>Main database - myDB<br>
  User database - userDB  (this is stored in a myDB.dbo.tblUserDatabase)<br>
  userDB has a table called tblUserReports</p>
  
  <p>I want to write something like this in dynamic sql:</p>
  
  <pre><code>SELECT * FROM userDB.dbo.tblUserReports
  </code></pre>
  
  <p>So tried: </p>
  
  <pre><code>declare @dbUser varchar(50)
  set @dbUser = (SELECT strDBName FROM myDB.dbo.tblUserDatabase)
  
  SELECT * FROM @dbUser.dbo.tblUserReports
  </code></pre>