Question

I exported a table to a server but I can't find the table. Maybe I didn't put the right destination database. How can I find this table if my server has multiple databases, without opening each one of them?

I use MS Sql Server Management Studio 2008.

Was it helpful?

Solution

Rough and dirty, but it would do the job.

-- Instructions. Replace "table_name_here" with actual table name
sp_MSforeachdb 'USE ?
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N''[table_name_here]'') AND OBJECTPROPERTY(id, N''IsUserTable'') = 1)
BEGIN
  PRINT ''Found in db ?''
END'

OTHER TIPS

One way

SELECT  DISTINCT DB_NAME(database_id) 
FROM [sys].[dm_db_index_operational_stats](NULL,NULL,NULL,NULL)
WHERE OBJECT_NAME(object_id,database_id) = 'table_name'

Or if you are reasonably confident it would be in the dbo schema in whichever database

SELECT name
FROM   sys.databases
WHERE  CASE
         WHEN state_desc = 'ONLINE' 
              THEN OBJECT_ID(QUOTENAME(name) + '.[dbo].[table_name]', 'U')
       END IS NOT NULL 

Based off Martin Smith's answer above but generalised into a view to give a sort of cross-DB version of sys.tables -

CREATE VIEW ListTablesAllDBs

AS

SELECT 
    DB_NAME(database_id) as DBName,
    OBJECT_SCHEMA_NAME(object_id,database_id) as SchemaName,
    OBJECT_NAME(object_id,database_id) as TableName
FROM
    [sys].[dm_db_index_operational_stats](NULL,NULL,NULL,NULL)

Now, if only I can work out a way to do the same for columns.......

EDIT - Ignore this, finding it sometimes misses tables altogether.

Minor clarification just to avoid headaches for those with 'SuperUsers' who don't know how to name DBs:

EXEC sp_MSForEachDB '
USE [?]
IF OBJECT_ID(''mytable'') IS NOT NULL AND
   OBJECTPROPERTY(OBJECT_ID(''mytable''), ''IsTable'') = 1
PRINT ''Found here: ?'''
select 'select * from '+name+'.sys.tables where name=
        ''[yourtable]'';' from sys.databases

Instead of [yourtable], type the name of the missing table, and run the result again.

EXEC sp_MSForEachDB '
USE ? 
IF OBJECT_ID(''mytable'') IS NOT NULL AND
   OBJECTPROPERTY(OBJECT_ID(''mytable''), ''IsTable'') = 1
    PRINT ''?''
'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top