Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Sp MSforeachDB
From Wiki
sp_MSForEachDB is an undocumented procedure so use it with caution. You can use sp_MSForEachDB to loop over all the database to run a query or a proc. For example if you want the count of all sysobjects in every database run this.
- EXEC sp_MSForEachDB ' select ''[?]'',count(*) from [?].dbo.sysobjects'
If you need to exclude the system databases then use this
- EXEC sp_MSForEachDB 'IF ''[?]'' NOT IN (''[master]'', ''[model]'', ''[msdb]'', ''[tempdb]'')
- select ''[?]'',count(*) from [?].dbo.sysobjects'
To list all the tables and all their columns in each database you can run this (might take a while to run)
- EXEC sp_MSForEachDB 'IF ''[?]'' NOT IN (''[master]'', ''[model]'', ''[msdb]'', ''[tempdb]'')
- select ''[?]'' as DB_name,table_name,column_name from [?].information_schema.columns
- order by 1,table_name,ordinal_position'
Contributed by: --SQLDenis 15:38, 31 May 2008 (GMT)
Part of SQL Server Programming Hacks
Section Undocumented but handy



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.