title: Dynamic SQL - Query different database depending on parameter
body: <p>I have a situation where I need to get data from one of over 100 database (all with the exact same schema) depending on a parameter passed to a stored procedure.</p>
  
  <p>The way I've been trying to do this is to build a dynamic SQL statement to execute with <code>sp_executesql</code>:</p>
  
  <p>(This is just a test script BTW):</p>
  
  <pre><code>declare @sql nvarchar(1000)
  set @sql = 'select top 10 * from [SERVER].@dbName.dbo.[LL]'
  exec sp_executesql @sql, N'@dbName nvarchar(50)', @dbName = N'[TheDatabase1]'
  </code></pre>
  
  <p>This gives the error <code>Incorrect syntax near '@dbName'.</code></p>
  
  <p>Is there any other option I might consider?</p>
  
  <p>PS - the database schema is not within my control.</p>