Technical Article

Quick table finder

,

Sometimes I need to find a table but I do not remember the database it is in as well as the full name of the table... So i had to put this little script together.

In the SELECT @tableName ='%[name]%' replace [name] with the table name you are looking for and run the script.

Also, if you replace all sys.tables in the script with sys.procedures you will be able to find any stored procedure.

DECLARE @dbName NVARCHAR(128),@tableName NVARCHAR(128),@sqlStmnt NVARCHAR(max)
DECLARE databaseNamesArr CURSOR FAST_FORWARD READ_ONLY FOR
SELECT [name]
FROM sys.databases WITH (NOLOCK)
ORDER BY [name] ASC

/****************************** CHANGE THE TABLE NAME HERE ********************/SELECT @tableName=N'%sysjobs%'
/******************************************************************************/
OPEN databaseNamesArr
FETCH    NEXT FROM databaseNamesArr INTO @dbName
WHILE @@FETCH_STATUS=0
BEGIN
    SELECT @sqlStmnt=
    N'use '+@dbName+' '+
    N' SET NOCOUNT ON'+
    N' DECLARE @tblName NVARCHAR(128)'+
    N' DECLARE tableNamesArr CURSOR FAST_FORWARD READ_ONLY FOR'+
    N' SELECT [name]'+
    N' FROM sys.tables WITH (NOLOCK)'+
    N' OPEN tableNamesArr'+
    N' FETCH NEXT FROM tableNamesArr INTO @tblName'+
    N' WHILE @@FETCH_STATUS=0'+
    N' BEGIN '+
    N'IF(PATINDEX(@tableName,@tblName)<>0)'+
        N' BEGIN '+
            N' SELECT QUOTENAME(@dbName)+''.''+QUOTENAME(t2.name)+''.''+QUOTENAME(t1.name)'+
            N' FROM sys.tables t1 WITH (NOLOCK) INNER JOIN sys.schemas t2 WITH (NOLOCK)'+

            N' ON t1.SCHEMA_ID=t2.SCHEMA_ID'+
            N' WHERE t1.NAME=@tblName'+
        N' END'+
        N' FETCH NEXT FROM tableNamesArr INTO @tblName'+
    N' END'+
    N' CLOSE tableNamesArr'+
    N' DEALLOCATE tableNamesArr'
    EXECUTE sp_executesql @sqlStmnt,N'@tableName NVARCHAR(128),@dbName NVARCHAR(128)',@tableName,@dbName
    FETCH NEXT FROM databaseNamesArr INTO @dbName
END
CLOSE databaseNamesArr
DEALLOCATE databaseNamesArr

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating