I remember a table by name PRODUCT_DETAILS and had made some analysis long back ago on this table. But now I dont know in which database it is created. I have FIVE SQL Servers and in each server we have around THIRTY databases. How do I search. So I explored to search table across all databases. Here is the script to search a table across all databases and display database name in which the specified table name exists.
SELECT name FROM sys.databases WHERE CASE WHEN state_desc = 'ONLINE'
THEN OBJECT_ID(QUOTENAME(name) + '.[dbo].[PRODUCT_DETAILS]', 'U') END IS NOT NULL
The above script searches when exact table name specified. When you know partial name we can useTHEN OBJECT_ID(QUOTENAME(name) + '.[dbo].[PRODUCT_DETAILS]', 'U') END IS NOT NULL
CREATE TABLE #temp_dbase_List(DatabaseName SYSNAME, TableName SYSNAME);
EXEC sp_msForEachDB 'INSERT #temp_dbase_List SELECT ''?'', TABLE_NAME
FROM [?].INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE=''BASE TABLE'';';
SELECT * FROM #temp_dbase_List where TableName like '%TableNameToSearch%' ORDER BY DatabaseName,TableName;
DROP TABLE #temp_dbase_List;
This is one more similar query populated from sys.tables. This will populate all tables across all databases.EXEC sp_msForEachDB 'INSERT #temp_dbase_List SELECT ''?'', TABLE_NAME
FROM [?].INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE=''BASE TABLE'';';
SELECT * FROM #temp_dbase_List where TableName like '%TableNameToSearch%' ORDER BY DatabaseName,TableName;
DROP TABLE #temp_dbase_List;
create table #tablelist (db sysname, tab sysname);
exec sp_msforeachdb '
use [?];
insert into #tablelist
select db_name(),name from sys.tables;'
select * from #tablelist
drop table #tablelist
exec sp_msforeachdb '
use [?];
insert into #tablelist
select db_name(),name from sys.tables;'
select * from #tablelist
drop table #tablelist
No comments:
Post a Comment