我有数百个 SQL select 语句存储在数据库表的一nvarchar列中。
对于每个 select 语句,我需要找出它们从哪些表中读取。我需要以编程方式执行此操作(例如使用 T-SQL)并将访问表的列表存储在数据库表中。
我通过调用存储过程开始执行此操作sp_describe_first_result_set。它只能部分起作用。
例如:
EXEC sp_describe_first_result_set
@tsql = 'SELECT
a.code, b.customer_name
FROM table_a a
INNER JOIN table_b b ON a.code = b.code
WHERE NOT EXISTS (SELECT 1
FROM table_c c
WHERE a.code = c.code)',
@params = null,
@browse_information_mode = 2
Run Code Online (Sandbox Code Playgroud)
这会返回source_table值table_a和table_b但不是table_c。
我需要访问表的列表。
关于我如何实现这一目标有什么想法吗?
Ste*_*ord 12
如何创建一个临时视图,然后使用内置的依赖函数来获取引用的表,然后删除视图,冲洗并重复,将 @sql 替换为您自己的语句:
declare @tsql varchar(max) = 'SELECT
a.code, b.customer_name
FROM table_a a
INNER JOIN table_b b ON a.code = b.code
WHERE NOT EXISTS (SELECT 1
FROM table_c c
WHERE a.code = c.code)'
exec ('create view vwtmp as ' + @tsql)
select OBJECT_NAME(referencing_id) referencing_entity,
o.[type_desc] as referenced_entity_type, referenced_entity_name
from sys.sql_expression_dependencies d
inner join sys.objects o
on d.referenced_id = o.[object_id]
where OBJECT_NAME(referencing_id) = 'vwtmp'
exec ('drop view vwtmp')
Run Code Online (Sandbox Code Playgroud)
这是我的测试返回的结果:
referencing_entity referenced_entity_type referenced_entity_name
------------------ ---------------------- ----------------------
vwtmp USER_TABLE table_a
vwtmp USER_TABLE table_b
vwtmp USER_TABLE table_c
Run Code Online (Sandbox Code Playgroud)