title: Loop through a list of databases and run SQL file(s)
body: <p>I have a number of databases on which I should run the same SQL file. The database names can be found in a table in another database. I was wondering if I can automate this somehow to avoid changing database manually and running the script. I'm trying to make following script working (in <code>sqlcmd</code> mode):</p>
  
  <pre><code>:On Error Exit
  declare @statement nvarchar(MAX), @dbname nvarchar(255)
  
  declare NameList cursor for
  select database_name  from databases where type ='s'
  OPEN NameList
  FETCH NEXT FROM NameList 
  INTO @dbname
  WHILE @@FETCH_STATUS = 0
   BEGIN
    SET @statement = N'USE '+@dbname+N'
    GO'
  
    EXEC dbo.sp_executesql @statement
  
    :r C:\temp\check_db.sql
    GO
    FETCH NEXT FROM NameList INTO @dbname
  END
  CLOSE NameList
  DEALLOCATE NameList
  </code></pre>
  
  <p>The idea is to go through the list of databases and use <code>USE &lt;DB&gt;</code> statement to change the current database to one fetched from the list, then run the script from SQL file. </p>
  
  <p>I'm getting error <code>Incorrect syntax near &lt;some point in SQL file&gt;.</code> which points a row in the SQL file thus I'm concluding that <code>USE &lt;DB&gt;</code> is not changing the current database for the SQL file.</p>