SQL query to list databases that have a given table
0
Q:
SQL query to list databases that have a given table
Hi all I need your help for creating some SQL query that returns the names of all databases that have a given table name.
Ex. I'd like to run this query against the master database and search for all databases that have a table called "customers".
Is it possible to do this, if yes how?
Thanks in advance
ASKED: Mar 20 2009  5:38 AM GMT
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
0
75 pts.
0
A:
 RATE THIS ANSWER
0
Click to Vote:
  •   0
  •  0
  • AddThis Social Bookmark Button
SELECT name
FROM master..sysdatabases

lists all databases on your server.

So you could just make a cursor on all databases and query if your table belongs to those. But ofcourse that implies your should have the neccessary rights to interrogate all databases.

DECLARE @name VARCHAR(50) -- database name
DECLARE db_cursor CURSOR FOR
SELECT name
FROM master..sysdatabases
ORDER BY name
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name

WHILE @@FETCH_STATUS = 0
BEGIN
exec ('use ' +@name+' SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
where table_name=''customers''
if @@rowcount<>0 select '''+@name+''' as DataBaseName')
FETCH NEXT FROM db_cursor INTO @name
END

CLOSE db_cursor
DEALLOCATE db_cursor



----------------------

from one query knowing all tables in all databases, i can't be sure but i don't think it exists
but you may run on any databse the below query, and you will know if such as this table exists in the chosen datase or doesn't

SELECT *
FROM sys.Tables
where name like 'customers%'
Last Answered: Mar 20 2009  11:29 AM GMT by Pingu   75 pts.
Latest Contributors: Sous   580 pts.
0
0
Discuss This Answer:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _



_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

Msi77   800 pts.  |   Mar 20 2009  10:28PM GMT

You can use undocumented SP_MSFOREACHDB stored proc. :

sp_msforeachdb @command1=’use[?];
SELECT table_catalog as DB, table_name
FROM information_schema.Tables
where table_name = ”customers”
‘

 
0