编写一个返回对象依赖关系的查询

时间:2009-12-16 18:01:48

标签: sql-server sql-server-2008 dependencies

我正在寻找管理工作室在“查看依赖关系”菜单中显示的内容。

  1. Management Studio连接到SQL Server 2008
  2. 右键单击对象并选择“查看依赖关系”
  3. 现在,您可以来回浏览依赖项。
  4. 如何以编程方式获取相同的信息? (一个SQL查询?)

5 个答案:

答案 0 :(得分:4)

Before you run the following query, replace <database_name> and <schema_name.function_name> with valid names

USE <database_name>;
GO
SELECT OBJECT_NAME(object_id) AS referencing_object_name
    ,COALESCE(COL_NAME(object_id, column_id), '(n/a)') AS referencing_column_name
    ,*
FROM sys.sql_dependencies
WHERE referenced_major_id = OBJECT_ID('<schema_name.function_name>')
ORDER BY OBJECT_NAME(object_id), COL_NAME(object_id, column_id);
GO

答案 1 :(得分:3)

这是另一种更简单的方法:

  SELECT DISTINCT
    O.ID ,
    O.Name AS TableName ,
    O.xtype
  FROM
    sysObjects O ( NOLOCK )
  INNER JOIN sysComments C ( NOLOCK ) ON O.ID = C.ID
  WHERE
    C.text LIKE '%<schema_name.function_name>%'
  ORDER BY
    XType ,
    TableName
Before you run the following query, replace <schema_name.function_name> with a valid name

答案 2 :(得分:2)

我知道这是一个较老的问题,但我也知道在提出自己的解决方案时我自己看了。

您可以使用sys.sql_dependencies表值函数,而不是使用已弃用的sys.dm_sql_referencing_entities

以下查询以递归方式调用它来跟踪依赖关系,显示依赖关系链中的每个步骤:

DECLARE @table varchar(max);
SET @table = 'schema.objectname';
;with 
DepsOn As (
    SELECT CAST(@table As varchar(max)) As parent
         , CAST(l1.referencing_schema_name 
               + '.' 
               + l1.referencing_entity_name As varchar(max)) As child
         , l1.referencing_class_desc As [description]
         , 0 As Depth
    FROM sys.dm_sql_referencing_entities(@table,'OBJECT') l1
    UNION ALL
    SELECT l2.child As parent
         , cast(l2ca.referencing_schema_name 
               + '.' 
               + l2ca.referencing_entity_name As varchar(max)) As child
         , l2ca.referencing_class_desc As [description]
         , l2.Depth + 1 As Depth
    FROM DepsOn l2
    CROSS APPLY sys.dm_sql_referencing_entities(l2.child,'OBJECT') l2ca
    )
SELECT *
FROM DepsOn

答案 3 :(得分:1)

查看sys和INFORMATION_SCHEMA表中的元数据。

this answerthis answerthis answer,这些都可能有用。

答案 4 :(得分:0)

经过测试的代码。 我运行它并运行我所需的输出

 SELECT referencing_schema_name, referencing_entity_name,
     referencing_id, referencing_class_desc, is_caller_dependent
     FROM sys.dm_sql_referencing_entities ('dbo.yourobject', 'OBJECT');
     GO

<强> VishalDream