Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a database with a particular table OR Find a table in every database of SQL Server

Tags:

sql

sql-server

I have a SQL Server with hundreds of databases and each database having hundreds of tables. Now I would like to find where in these databases is a table that I am looking for.

I could find if a table existed in individual database using

use myDatabase 
select * from sys.tables  where name = 'mytable' 
GO

but using this means I have to manually change the database for hundreds of times . I would like to find the database name only. Is there a way out ?

like image 390
Thunder Avatar asked Jan 19 '11 08:01

Thunder


People also ask

How do you find the datafile which contains a particular table?

If you query DBA_EXTENTS based on segment_name equal to your table name you will see that the column FILE_ID will show you the database file where each extent is located. You can then use FILE_ID to query DBA_DATA_FILES to find the name of the datafile.


2 Answers

SELECT DISTINCT  DB_NAME(database_id)
FROM [sys].[dm_db_index_operational_stats](NULL,NULL,NULL,NULL) 
WHERE OBJECT_NAME(object_id,database_id) = 'mytable'
like image 70
Martin Smith Avatar answered Oct 13 '22 14:10

Martin Smith


Okay, if you're just wanting to find each database that contains a particular table, and aren't going to be querying the table, then you can just do:

create table #t (
    DBName sysname not null
)
go
exec sp_MSforeachdb 'use [?]; if OBJECT_ID(''dbo.mytable'') is not null insert into #t (DBName) select ''?'''
go
select * from #t
go
drop table #t

(If you're not using multiple schemas in your databases, you won't need to specify dbo in the OBJECT_ID call, otherwise I use it to avoid finding tables in the wrong schema)

like image 35
Damien_The_Unbeliever Avatar answered Oct 13 '22 13:10

Damien_The_Unbeliever