Find an object in SQL Server (cross-database)

后端 未结 10 1204
太阳男子
太阳男子 2021-02-01 16:52

If I\'ve been told a table (or proc) name, but not which connected database the object is located in, is there any simple script to search for it? Maybe search somewhere in the

10条回答
  •  面向向阳花
    2021-02-01 17:42

    There is a schema called INFORMATION_SCHEMA schema which contains a set of views on tables from the SYS schema that you can query to get what you want.

    A major upside of the INFORMATION_SCHEMA is that the object names are very query friendly and user readable. The downside of the INFORMATION_SCHEMA is that you have to write one query for each type of object.

    The Sys schema may seem a little cryptic initially, but it has all the same information (and more) in a single spot.

    You'd start with a table called SysObjects (each database has one) that has the names of all objects and their types.

    One could search in a database as follows:

    Select [name] as ObjectName, Type as ObjectType
    From Sys.Objects
    Where 1=1
        and [Name] like '%YourObjectName%'
    

    Now, if you wanted to restrict this to only search for tables and stored procs, you would do

    Select [name] as ObjectName, Type as ObjectType
    From Sys.Objects
    Where 1=1
        and [Name] like '%YourObjectName%'
        and Type in ('U', 'P')
    

    If you look up object types, you will find a whole list for views, triggers, etc.

    Now, if you want to search for this in each database, you will have to iterate through the databases. You can do one of the following:

    If you want to search through each database without any clauses, then use the sp_MSforeachdb as shown in an answer here.

    If you only want to search specific databases, use the "USE DBName" and then search command.

    You will benefit greatly from having it parameterized in that case. Note that the name of the database you are searching in will have to be replaced in each query (DatabaseOne, DatabaseTwo...). Check this out:

    Declare @ObjectName VarChar (100)
    
    Set @ObjectName = '%Customer%'
    
    Select 'DatabaseOne' as DatabaseName, [name] as ObjectName, Type as ObjectType
    From DatabaseOne.Sys.Objects
    Where 1=1
        and [Name] like @ObjectName
        and Type in ('U', 'P')
    
    UNION ALL
    
    Select 'DatabaseTwo' as DatabaseName, [name] as ObjectName, Type as ObjectType
    From DatabaseTwo.Sys.Objects
    Where 1=1
        and [Name] like @ObjectName
        and Type in ('U', 'P')
    
    UNION ALL
    
    Select 'DatabaseThree' as DatabaseName, [name] as ObjectName, Type as ObjectType
    From DatabaseThree.Sys.Objects
    Where 1=1
        and [Name] like @ObjectName
        and Type in ('U', 'P')
    

提交回复
热议问题