While Loop to Iterate through Databases

I would consider sp_MSForEachDB which is a lot easier...

Edit:

EXEC sp_MSForEachDB 'USE [?]; IF DB_NAME() LIKE ''Z%%''
BEGIN


END
'

CREATE TABLE #T
(dbname sysname NOT NULL PRIMARY KEY,
SumPGCOUNT INT,
CREATED DATETIME)

DECLARE @Script NVARCHAR(MAX) = ''

SELECT @Script = @Script + '

USE ' + QUOTENAME(name) + '
IF EXISTS(SELECT * FROM sys.tables WHERE OBJECT_ID=OBJECT_ID(''dbo.tbldoc''))
  INSERT INTO #T
  SELECT db_name() AS dbname, SUM(PGCOUNT) AS SumPGCOUNT, CREATED 
  FROM dbo.tbldoc
  GROUP BY CREATED;  
  '
FROM sys.databases 
WHERE state=0 AND user_access=0 and has_dbaccess(name) = 1
 AND [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
ORDER BY [name]

IF (@@ROWCOUNT > 0)
 BEGIN
 --PRINT @Script
 EXEC (@Script)
 SELECT * FROM #T
 END

 DROP TABLE #T

My code to search for data from more than one database would be:

use [master]

go

if object_id('tempdb.dbo.#database') is not null 

    drop TABLE #database

go

create TABLE #database(id INT identity primary key, name sysname)

go

set nocount on

insert into #database(name)

select name

from sys.databases

where name like '%tgsdb%' --CHANGE HERE THE FILTERING RULE FOR YOUR DATABASES!

and source_database_id is null

order by name

Select *
from #database

declare @id INT, @cnt INT, @sql NVARCHAR(max), @currentDb sysname;

select @id = 1, @cnt = max(id)
from #database

while @id <= @cnt

BEGIN

        select @currentDb = name
    from #database
    where id = @id

    set @sql = 'select Column1, Column2 from ' + @currentDb + '.dbo.Table1'
    print @sql
    exec (@sql);
    print '--------------------------------------------------------------------------'
    set @id = @id + 1;

END

go

Tags:

Sql

Sql Server