title: Looping through list of database to drop and recreate a view
body: <p>I am unsure if it is possible to do this with a loop in TSQL.</p>
  
  <p>I have a list of Databases I would like to loop through and for each database drop and recreate the view as necessary.</p>
  
  <p>I have a script already to drop and recreate the view. However, presently at the top of my script I have a bunch of use statements and i just go down the list uncommenting and reruning the script. However I would like to automate it so it would be much faster. I have done a similar thing in the past looping though a string of database names and using it to execute a use statement. Which works except when creating views because the view has to be seperated by go statements. Here is a code snippet of my code to parse databases any help to make work with views would be great.</p>
  
  <pre><code>DECLARE @DBs AS VARCHAR(MAX);
  DECLARE @OneDB AS VARCHAR(255);
  DECLARE @CmdToExec AS VARCHAR(MAX);
  
  SET @DBs = 'db1,db2,db3,db4,db5,db6,db7,db8,db9,db10,db11,db12,db13,db14,db15,db16'
  
  DECLARE DB_Cursor CURSOR FOR
      SELECT SUBSTRING( ',' + @DBs + ',', n + 1,
          CHARINDEX( ',', ',' + @DBs + ',', n + 1 ) - n - 1 ) AS "dbInfo"
      FROM CommunityPAL.dbo.Numbers
      WHERE SUBSTRING( ',' + @DBs + ',', n, 1 ) = ','
          AND n &lt; LEN( ',' + @DBs + ',' );
  OPEN DB_Cursor;
  FETCH NEXT FROM DB_Cursor INTO @OneDB;
  WHILE @@FETCH_STATUS = 0
  BEGIN
      SET @CmdToExec = 'USE ' + @OneDB;
      EXEC @CmdToExec;
  
      --statements to execute
  
      FETCH NEXT FROM DB_Cursor INTO @OneDB;
  END
  CLOSE DB_Cursor
  DEALLOCATE DB_Cursor
  </code></pre>