SQL Server 2005 script to iterate through all the databases on a server
- produce a SQL script
- run it on all appropriate databases
- display the output
DECLARE @DBName varchar(300)
DECLARE @SQL varchar(max)
DECLARE @tableName VARCHAR(255)SET @Loop = 1
SET @DBName = '' WHILE @Loop = 1
BEGIN SELECT TOP 1 @DBName = d.Name
FROM master.sys.databases d
WHERE d.Name > @DBName
AND d.database_id not in (1, 2, 3, 4)
ORDER BY d.Name SET @Loop = @@ROWCOUNT IF @Loop = 0
BREAK SET @SQL =
'IF EXISTS (SELECT 1 FROM [' + @DBName + '].sys.objects WHERE [name] = ''ErrorLog'')
BEGIN
SELECT ''' + @@SERVERNAME + ''', ''' + @DBName + ''', ErrorMessage, ErrorDate
FROM [' + @DBName + '].dbo.ErrorLog
END
ELSE
BEGIN
PRINT ''ErrorLog table does not exist on server: ' + @@SERVERNAME + ' and database: ' + @DBName + '''
END ' BEGIN TRY
EXEC master.dbo.sp_executeSQL @SQL
END TRY
BEGIN CATCH
PRINT 'Error executing ' + @SQL + ' on server: ' + @@SERVERNAME + ' for database: ' + @DBName
END CATCH
END