我正在查找Management Studio顯示的「View Dependencies」菜單。編寫一個查詢,返回對象的依賴關係
- Management Studio中連接到SQL Server 2008
- 右擊對象,並選擇「視圖依賴性」
- 現在,您可以通過依賴來回導航。
如何以編程方式獲取相同的信息? (一個SQL查詢?)
我正在查找Management Studio顯示的「View Dependencies」菜單。編寫一個查詢,返回對象的依賴關係
如何以編程方式獲取相同的信息? (一個SQL查詢?)
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
查看sys和INFORMATION_SCHEMA表中的元數據。
有this answer,this answer和this answer,這可能都是有用的。
這裏是另一種更簡單的方法:
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
我知道這是一個老問題,但我也知道,我看着它自己,而未來與自己的解決方案。
您可以使用表值函數sys.dm_sql_referencing_entities
而不是使用已棄用的sys.sql_dependencies
。
以下查詢調用它遞歸跟蹤下的依賴關係,示出了在依賴關係鏈中的每個步驟:
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
測試的代碼。 我運行它,並去了我需要的輸出
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
是的......我已經看到了幾種解決方案......但我不能懶惰,要的防彈解決方案沒有我做試驗和錯誤:-) – Nestor 2009-12-16 18:07:01
沒問題 - 你問如何qrite一個查詢 - 不給我一個! ;-) – 2009-12-16 18:13:33