Login or Sign Up to become a member!
LessThanDot Site Logo


Community Wiki

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.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot facebook Lessthandot rss

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


Google Ads

Sp MSforeachDB

From Wiki

Jump to: navigation, search

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.

  1. EXEC sp_MSForEachDB ' select ''[?]'',count(*) from [?].dbo.sysobjects'

If you need to exclude the system databases then use this

  1. EXEC sp_MSForEachDB 'IF ''[?]'' NOT IN (''[master]'', ''[model]'', ''[msdb]'', ''[tempdb]'')
  2. 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)

  1. EXEC sp_MSForEachDB 'IF ''[?]'' NOT IN (''[master]'', ''[model]'', ''[msdb]'', ''[tempdb]'')
  2. select ''[?]'' as DB_name,table_name,column_name from [?].information_schema.columns
  3. 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

282 Rating: 2.7/5 (85 votes cast)