Link to home
Start Free TrialLog in
Avatar of samprg
samprg

asked on

Search in Databases

Hi,

I have many databases, I wanna use this query in the below, how?
Thanks
select name
from t1
where name='David'
Avatar of samprg
samprg

ASKER

I wanna use the query in all the databases
you can try using msforeachdb

EXEC sp_MSforeachdb 'IF EXISTS(SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(''T1'') Select name from [?]..t1 where name = ''David'''
missed a bracket there

EXEC sp_MSforeachdb 'IF EXISTS(SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(''T1'')) Select name from [?]..t1 where name = ''David'''
Avatar of samprg

ASKER

Perfect, but I need to add a database name
then do it like this

EXEC sp_MSforeachdb 'IF EXISTS(SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(''T1'')) Select db_name(), name from [?]..t1 where name = ''David'''

select 'select name from ' + d.name + '.dbo.t1 where name = ' + char (39) + 'david'+ char (39) + '; '
from sys.databases d
where d.name not in ('master', 'model', 'msdb', 'tempdb')
order by 1;

Open in new window

sorry, it should be

EXEC sp_MSforeachdb 'IF EXISTS(SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(''T1'')) Select ? as dbname, name from [?]..t1 where name = ''David'''
Avatar of samprg

ASKER

ralmada,
Gives me error
Invalid column name
Avatar of samprg

ASKER

jorgedeoliveiraborges,

Does not work
ASKER CERTIFIED SOLUTION
Avatar of ralmada
ralmada
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of samprg

ASKER

Awesome
>> jorgedeoliveiraborges,
>> Does not work
Sorry.

select 'select name from ' + d.name + '.dbo.t1 where name = ' + char (39) + 'david'+ char (39) + '; '
from master.sys.databases d
where d.name not in ('master', 'model', 'msdb', 'tempdb')
order by 1;

Open in new window