title: SQL Server cursor - loop through multiple servers and execute query
body: <p>I have the following code (cursor): </p>
  
  <pre><code>DECLARE @SN VARCHAR(20);
  DECLARE @sql NVARCHAR(MAX); 
  DECLARE C CURSOR LOCAL FAST_FORWARD
    FOR SELECT DISTINCT(SERVERNAME) FROM INSTALLATION 
      where DATABASETYPE = 'MsSql' AND SERVERNAME IN ('x');
  
  OPEN C;
  
  FETCH NEXT FROM C INTO @SN;
  WHILE (@@FETCH_STATUS = 0)
  BEGIN 
      PRINT @SN;
      -- you could loop here for each database, if you'd define what that is
     SELECT name 
  FROM master.dbo.sysdatabases 
  WHERE name not in ('master','model','msdb','tempdb');
      SET @sql = N'SELECT TOP 1 NAME FROM TABLE ';
  
      EXEC sp_executesql @sql;
      FETCH NEXT FROM C INTO @SN;
  END 
  CLOSE C;
  DEALLOCATE C;
  </code></pre>
  
  <p>I would like to be able to loop through every server and execute a select statement on some (not all) of their databases.</p>
  
  <p>The query is something like: </p>
  
  <pre><code>SELECT TOP 1 NAME FROM TABLE 
  </code></pre>
  
  <p>The server from where I am running the cursor has all the others as linked servers.</p>