Monday, September 14, 2009

Executing query in all Databases in an SQL Server

If you want to run a particular SQL in all databases in side an SQL Server, use

EXEC sp_MsForEachDb 'SELECT ''?'' AS DatabaseName, COUNT(*) AS ObjectCount FROM ?.dbo.sysobjects'

Also if you want to filter the database based on some criteria then,

EXEC sp_MSForEachDb 'IF EXISTS(SELECT 1 FROM ?.dbo.sysobjects WHERE NAME=''CommonTableName'' AND Type=''U'') SELECT ''?'' AS DBName'


More info Refer - http://www.4guysfromrolla.com/articles/090909-1.aspx

No comments:

Post a Comment