One way to do this: use sp_msForEachDb.
- Round 1 -------
Call this system procedure with the varchar parameter. (This is actually a LOT messier than this, check the code in the main database if you want to know what it really does.) The parameter should be a snippet of dynamic code - for example,
DECLARE @DemoParameter varchar(1000) SET @DemoParameter = 'SELECT MyCol from MyTable where CreatedOn between ''Jan 1, 1980'' and ''Dec 21, 2012''' EXECUTE sp_msForEachDb @DemoParameter
This will cause a query to each database of the SQL instance, returning one set for each database - with the exception of those databases in which there was no necessary table (s) that would cause an error (in particular, system databases), This leads us to...
- Round 2 ---------
Inside the dynamic code, since the databases are repeated in all instances of the question mark? will be replaced with the name of the database currently being processed. You can use this to filter which databases should be processed and which should not. Also note that the "current" database will not be modified by the subroutine; you must do this yourself. This gives us code like:
SET @DemoParameter = ' IF ''?'' like ''%Foo%'' BEGIN USE ? SELECT MyCol from MyTable where CreatedOn between ''Jan 1, 1980'' and ''Dec 21, 2012'' '
This will only result in querying those databases whose names contain the characters "foo". Perhaps you can check for a table in each database; other methods suggest.
This will allow you to drop one data set for each database, which does not help much if you need all of them in one neat and orderly data set, and this forces us ...
- Round 3 ------------
In short: create a temporary table and populate it from a dynamic query. As I will show below, you can include the database name and always the server name - it is very useful when your searches for lost data in dozens of databases extend to several servers.
Create (or clear) the temp table:
IF object_id('tempdb.dbo.##Foo') is null CREATE TABLE ##Foo ( ServerName varchar(100) not null ,DBName varchar(100) not null -- Add your own columns here ,MyCol int not null ) ELSE --Option: Delete this line to not clear on each run TRUNCATE TABLE ##Foo
Run the code (this is my main template, you can easily work with @DemoParameter):
EXECUTE sp_msForEachDB ' IF ''?'' like ''%Foo%'' BEGIN USE ? INSERT ##Foo select @@servername, db_name() ,MyCol from MyTable END '
... and this should create a single temporary table with your data. Check this out, I wrote this without actually testing the code, and typso will be silp in. (# temp tables should work just like ## temp, I usually do this with special system support problems)