title: Script -> Query for multiple databases
body: <p>I have the following problem: I want to execute a query on multiple databases on my SQL Server. Every customer has a separate database. Those all have exactly the same table and their names are similar. So there is a database <code>kde_01_Miller</code>, then a <code>kde_02_Mueller</code> and so on ...</p>
  
  <p>I want to execute a query in every one of those databases.</p>
  
  <p>Here's what I have tried:</p>
  
  <pre><code>DECLARE @name VARCHAR(100) -- database name
  DECLARE @dothis nvarchar(200)
  
  DECLARE db_cursor CURSOR FOR
  SELECT name
  FROM master.dbo.sysdatabases
  WHERE name like 'kde_0%'
  order by name
  
  OPEN db_cursor  
  FETCH NEXT FROM db_cursor INTO @name  
  
  WHILE @@FETCH_STATUS = 0
  BEGIN  
         set @dothis = 'use [' + @name + ']'
         exec sp_executesql @dothis
  
         /* Start query */
         select description from dbo.basicdata
         /* End query */
  
         FETCH NEXT FROM db_cursor INTO @name  
  END  
  
  CLOSE db_cursor  
  DEALLOCATE db_cursor
  </code></pre>
  
  <p>The problem is that the query does not work properly. The <code>use</code> statement seems not to be working. I get a result for every database I have, but the result is always the same one, dependent on the database I'm currently doing a query for.</p>
  
  <p>I've also tried the following and it worked: Instead of my while-loop I did this:</p>
  
  <pre><code>WHILE @@FETCH_STATUS = 0
  BEGIN  
         set @dothis= 'select description from ' + QUOTENAME(@name) + '.dbo.basicdata'
         exec sp_executesql @dothis
  
         FETCH NEXT FROM db_cursor INTO @name  
  END 
  </code></pre>
  
  <p>But I don't like this way, because you need the <code>quotename(@name)</code> for every table.</p>
  
  <p>How do I make the first example work?</p>