DECLARE @Database VARCHAR(255) DECLARE @DBList TABLE (DBName varchar(255), Processed CHAR(1))-- Populate the in-memory table @DBList with all of the database namesinsert @DBListSelect [name] , 'N' from master..sysdatabases where [name] NOT IN( 'model','master','tempdb','msdb')--select * from @DBList -- DEBUG: Run this to prove population was successful-- Grab the first DB name from our in-memory tableWhile EXISTS (Select top 1 DBName from @DBList where Processed='N' order by DBName)BEGIN-- Get the DB Name into the @Database variableSet @Database = (Select top 1 DBName from @DBList where Processed='N' order by DBName)-- Do whatever awesome stuff with the database...print @Database-- Update the Processed flag to skip this DB on the next WHILE pass. Ever-decreasing listUpdate @DBList set Processed='Y' where DBName = @DatabaseEND
WHILE (@@FETCH_STATUS = 0)