About Me

My photo
a Dynamic and Energetic guy.....

Monday, June 13, 2016

Search a SQL TABLE within ALL SQL Databases

When we want to find a TABLE among all DATABASES there is no such query.
In that case we have to JOIN SYS.TABLES and SYS.SCHEMAS.
We can use following SQL Script to FIND tables Named as 'SOCIAL'.

================================================================================================================================================
SET NOCOUNT ON
DECLARE @AllTables table (DbName sysname,SchemaName sysname, TableName sysname)
DECLARE
     @SearchDb nvarchar(200)
    ,@SearchSchema nvarchar(200)
    ,@SearchTable nvarchar(200)
    ,@SQL nvarchar(4000)
SET @SearchDb='%'
SET @SearchSchema='%'
SET @SearchTable='%SOCIAL%'
SET @SQL='select ''?'' as DbName, s.name as SchemaName, t.name as TableName from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id WHERE ''?'' LIKE '''+@SearchDb+''' AND s.name LIKE '''+@SearchSchema+''' AND t.name LIKE '''+@SearchTable+''''

INSERT INTO @AllTables (DbName, SchemaName, TableName)
    EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY DbName, SchemaName, TableName




Can see the RESULTS.

No comments:

My Masters