我有许多使用CTE,临时表,表变量和子查询的存储过程,我需要获取存储过程中使用的所有列(包括数据库,模式和表/视图)的列表。我不需要获取临时表,表变量或CTE中的列。我只需要在我的服务器上的数据库中的表或视图中定义的引用列。
我尝试了sys.dm_sql_referenced_entities
和sys.sql_expression_dependencies
,但他们没有在第一个选择查询后返回列或在CTE中选择。
答案 0 :(得分:0)
这是我用来获取存储过程中使用的所有表但不返回列的内容。
declare
@target_table as varchar(255) = N'my_sp',
@target_schema as varchar(255) = N'dbo';
select distinct od.name as depname
,1 as depnumber
,od.type as deptype
,sd.name as depschemaname
from sys.objects as o
inner join sys.schemas as s
on s.schema_id = o.schema_id
inner join sys.objects as od
on od.object_id = o.parent_object_id
inner join sys.schemas as sd
on sd.schema_id = od.schema_id
where s.name = @target_schema
and o.name = @target_table and od.type = 'U'
union
select distinct od.name as depname
,case
when od.type = 'P'
then np.procedure_number
else 1
end as depnumber
,od.type as deptype
,sd.name as depschemaname
from sys.sql_expression_dependencies d
inner join sys.objects o
on o.object_id = d.referencing_id
inner join sys.schemas s
on s.schema_id = o.schema_id
inner join sys.objects od
on od.object_id = d.referenced_id
inner join sys.schemas sd
on sd.schema_id = od.schema_id
left join sys.numbered_procedures np
on np.object_id = d.referenced_id
where s.name = @target_schema
and o.name = @target_table and od.type = 'U';