Find all references to an object in an SQL Server

2020-02-08 00:52发布

问题:

I'm trying to find all references to an object in an SQL Server database.

How can I quickly search? SQL Server Management Studio does not seem to do it. I use http://www.red-gate.com/products/SQL_Search/ but I'd like to find the "official" Microsoft solution to this. Is it in another product?

For example, when I do a mass search in visual studio, I would like to be able to also find something in all stored procedures.

Or maybe I'm not coding this the right way?

Carl

回答1:

Use:

select object_name(m.object_id), m.*
  from sys.sql_modules m
 where m.definition like N'%name_of_object%'

...because SYSCOMMENTS and INFORMATION_SCHEMA.routines have nvarchar(4000) columns. So if "name_of_object" is used at position 3998, it won't be found. SYSCOMMENTS does have multiple lines, but INFORMATION_SCHEMA.routines truncates.



回答2:

In SQL 2008 the DMV (Data Management Function) sys.dm_sql_referencing_entities was added. Its returns any object that references the object you pass it.

SELECT * FROM sys.dm_sql_referencing_entities('dbo.Table1', 'OBJECT')


回答3:

SQL Server Management Studio has a View Dependencies feature when you right click on an object in the Object Explorer. Is this what you're looking for?



回答4:

With the use of an undocumented SQL sp: sp_msforeachdb

exec sp_msforeachdb '
USE [?];

--IF DB_NAME() NOT IN (''master'',''tempdb'',''model'',''msdb'')
BEGIN
DECLARE 
    @SearchStr varchar(100) 
    SET @SearchStr = ''%column_store_segments%''; 
SELECT DISTINCT
    ''?'' as db_name, o.name
    , ( CASE upper(o.xtype) 
            WHEN ''C'' THEN ''CHECK constraint''        
            WHEN ''D'' THEN ''Default or DEFAULT constraint''                       
            WHEN ''F'' THEN ''FOREIGN KEY constraint''  
            WHEN ''L'' THEN ''Log''                                                                 
            WHEN ''FN'' THEN ''Scalar function''        
            WHEN ''IF'' THEN ''Inline table-function''
            WHEN ''PK'' THEN ''PRIMARY KEY or UNIQUE constraint''
            WHEN ''P'' THEN ''Stored procedure''                                            
            WHEN ''R'' THEN ''Rule''                    
            WHEN ''RF'' THEN ''Replication filter stored procedure''            
            WHEN ''S'' THEN ''System table''            
            WHEN ''TF'' THEN ''Table function''
            WHEN ''TR'' THEN ''Trigger''                
            WHEN ''U'' THEN ''User table''      
            WHEN ''V'' THEN ''View''                    
            WHEN ''UQ'' THEN ''UNIQUE constraint (type is K)''                  
            WHEN ''X'' THEN ''Extended stored procedure''                           
        ELSE upper(o.xtype) END ) Type
    , ( CASE upper(o.xtype)
            WHEN ''PK'' THEN ( select object_name(parent_object_id) FROM sys.key_constraints (nolock) WHERE o.name=name )
            WHEN ''F'' THEN ( select object_name(parent_object_id) FROM sys.foreign_keys (nolock) WHERE o.name=name )
            WHEN ''TR'' THEN ( select object_name(parent_id) FROM sys.triggers (nolock) WHERE o.name=name )     
        ELSE '''' END ) as Parent_Object
FROM sysobjects o (nolock) 
INNER JOIN syscomments sc (nolock) ON o.id = sc.id
WHERE UPPER( text ) LIKE UPPER( @SearchStr ) AND substring(o.name,1,3)<> ''dt_'' 
GROUP BY o.name, o.xtype
END'
GO


回答5:

Very late to the party, but...

You can use the system proc sys.sp_depends:

exec sys.sp_depends 'object_name'

The result is a table listing all of the database objects that depend on (i.e., reference) object_name. Each row contains the name and type of the referring object, along with other info columns, depending on the type of object_name.


Note: This proc was added in MS SQL Server 2008.

See: MSDN docs

The docs say that this proc may be removed in a future release, and to use sys.dm_sql_referencing_entities instead, but it's still alive and kicking in MS SQL 2017.



回答6:

I use this query to look for all tables (or text) in the stored procedures:

SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'


回答7:

If you want to use OMG Ponies sql as a keyboard shortcut in SSMS, add the following SP to your master db.

USE [master]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FindAllReferences]
@targetText nvarchar(128)
AS
BEGIN
    SET NOCOUNT ON;

    declare @origdb nvarchar(128)
    select @origdb = db_name()

    declare @sql nvarchar(1000)

    set @sql = 'USE [' + @origdb +'];' 
    set @sql += 'select object_name(m.object_id), m.* '
    set @sql += 'from sys.sql_modules m  where m.definition like N' + CHAR(39) + '%' + @targetText + '%' + CHAR(39)

    exec (@sql)

    SET NOCOUNT OFF;
END

Then you just need to add dbo.SP_FindAllReferences to your keyboard shortcuts and then you can use it in the context of any DB on your server.

Cheers!

NB: If you are using SQL Server 2005 you will have to replace

@sql +=

with

@sql = @sql +


回答8:

I found a solution like this..

USE [Database]
GO

SELECT
referencing_schema_name = SCHEMA_NAME(o.SCHEMA_ID),
referencing_object_name = o.name,
referencing_object_type_desc = o.type_desc,
referenced_schema_name,
referenced_object_name = referenced_entity_name,
referenced_object_type_desc = o1.type_desc,
referenced_server_name, referenced_database_name
--,sed.* -- Uncomment for all the columns
FROM
sys.sql_expression_dependencies sed
INNER JOIN
sys.objects o ON sed.referencing_id = o.[object_id]
LEFT OUTER JOIN
sys.objects o1 ON sed.referenced_id = o1.[object_id]
WHERE
referenced_entity_name = 'SP_Pay_GetData'
order by referencing_object_name

http://blog.sqlauthority.com/2012/12/02/sql-server-find-referenced-or-referencing-object-in-sql-server-using-sys-sql_expression_dependencies/



回答9:

I'm not sure of 'official microsoft' way but I've used SqlDigger in the past. It's not bad.

If you want to do it in VS, then you will need the text of all your procs included in your project.



回答10:

In SQL Server 2000 here is a query that can search inside object definitions, supporting search strings of up to 2000 characters. It uses the chunks in the syscomments table.

SELECT O.name, O.xtype
FROM sysobjects O
WHERE EXISTS (
   SELECT *
   FROM
      (
         SELECT
            Chunk = Substring(C1.text, T.Offset, 4000)
                + Coalesce(Substring(C2.text, 1, T.AdditionalLength), '')
         FROM
            syscomments C1
            CROSS JOIN (
               SELECT 1, 0
               UNION ALL
               SELECT 2001, 2000
            ) T (Offset, AdditionalLength)
            LEFT JOIN syscomments C2
               ON C1.id = C2.id
               AND C1.colid + 1 = C2.colid
               AND T.Offset > 1
         WHERE
            O.id = C1.id
      ) C
   WHERE
      Chunk LIKE '%search string%'
);