I’m trying to get a list of databases on my server whose database contains the table “Foobar”. The snag I’m running into is that I can’t figure out how to use @CurrDB in conjunction with INFORMATION_SCHEMA. Any suggestions?
DECLARE @CurrDB varchar(255)
DECLARE RecSet CURSOR FOR
Select [name] FROM master..sysdatabases
OPEN RecSet
Fetch NEXT FROM RecSet Into @CurrDB
WHILE (@@FETCH_STATUS = 0)
BEGIN
Fetch NEXT FROM RecSet Into @CurrDB
IF (EXISTS (SELECT * FROM @CurrDB..INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Foobar'))
BEGIN
print @CurrDB
--do other stuff
END
END
Close RecSet
DEALLOCATE RecSet
Try this:
You could also use the following code to fill a table variable with a list of database names.