• Nice use of MS_ForEachDB here. We don't use it much here because it's undocumented and can be a little picky with syntax. We use this type of construct to loop DBs:

    DECLARE @databases TABLE(dbName VARCHAR(100))

    DECLARE @CurrentDB VARCHAR(100), @SQL NVARCHAR(max)

    --Exclude system DBs

    INSERT @databases SELECT name from sys.databases WHERE database_id > 4

    WHILE EXISTS (SELECT TOP 1 dbName FROM @databases)

    BEGIN

    SET@CurrentDB = (SELECT TOP 1 dbName FROM @databases)

    SET @SQL = 'Use ' + @CurrentDB + '; <Take some action>'

    --PRINT @sql

    EXEC sp_executesql @SQL

    DELETE @databases WHERE dbName = @CurrentDB

    END

    Ken