2

我有数百个 SQL Server 存储过程和脚本文件,我需要为每一个确定它们使用的确切表和列。这并不容易完成,因为 SQL 很复杂,而且许多表都有同名的列等......

我发现下面的 SQL 用于存储过程将告诉我它使用哪些表,但是我需要深入到列级别并打了一个空白。

有没有人有任何 SQL 脚本可以实现这一点,或者实际上一些 .NET 代码也可以,因为我们可以用一个小应用程序将它编织进去。

SELECT 
    OBJECT_NAME(referencing_id) AS referencing_entity_name, 
    o.type_desc AS referencing_desciption, 
    COALESCE(COL_NAME(referencing_id, referencing_minor_id), '(n/a)') AS referencing_minor_id, 
    referencing_class_desc, referenced_class_desc,
    referenced_server_name, referenced_database_name, referenced_schema_name,
    referenced_entity_name, 
    COALESCE(COL_NAME(referenced_id, referenced_minor_id), '(n/a)') AS referenced_column_name,
    is_caller_dependent, is_ambiguous
FROM 
    sys.sql_expression_dependencies AS sed
INNER JOIN 
    sys.objects AS o ON sed.referencing_id = o.object_id
WHERE 
    referencing_id = OBJECT_ID(N'MySchenma.MyStoredProcedure');
4

1 回答 1

1
select distinct
  object_name(objs.referencing_id) as referencing_entity_name,
  cols.referenced_entity_name,
  cols.referenced_minor_name
from
  sys.sql_expression_dependencies objs
  outer apply sys.dm_sql_referenced_entities( OBJECT_SCHEMA_NAME(objs.referencing_id) + N'.' + object_name(objs.referencing_id), N'OBJECT' ) as cols
where
  objs.referencing_id = object_id(N'MySchenma.MyStoredProcedure')
order by
  object_name(objs.referencing_id)
  cols.referenced_entity_name,
  cols.referenced_minor_name
;
于 2013-05-22T11:48:32.387 回答