[英]Way to get all table and column names from the T-SQL query
I have very large query (here are used more than 100 tables and thousands of columns), and I need to get list of all columns and tables used in this query. 我有一个非常大的查询(这里使用了100多个表和数千个列),我需要获取此查询中使用的所有列和表的列表。 Maybe there is any already created software or script to achieve that? 也许有任何已经创建的软件或脚本可以实现这一目标?
For example: 例如:
Query: 查询:
SELECT t1.Col1, t1.Col2, t1.Col3, t2.Col4, t2.Coln
FROM TableName1 t1
JOIN TableName2 t2 ON t1.Col1 = t2.Col4
Output should be: 输出应为:
TableName1
Col1
Col2
Col3
TableName2
Col4
Coln
I agree with the comments asking why you need such information and why a query would need to query so many tables. 我同意这些评论,询问为什么需要这些信息以及为什么查询需要查询这么多表。 That aside, this is still solvable. 除此之外,这仍然可以解决。
Some low-tech ways would be: 一些低技术的方法是:
dbo.table_name
), which they should be for best performance, search for your schema in a text editor, or write a small shell script to parse the query text for dbo
. 如果查询中引用的所有表都符合模式要求(例如dbo.table_name
),则应将它们获得最佳性能,请在文本编辑器中搜索您的模式,或者编写一个小的Shell脚本来解析dbo
的查询文本。 But this is what I would do. 但这就是我要做的。 This is probably the simplest and most reliable. 这可能是最简单,最可靠的。 Put the query into a stored procedure, install the procedure, and check its dependencies. 将查询放入存储过程中,安装该过程,然后检查其依赖性。
In SQL Server Management Studio, if you right-click a stored procedure, there is a 'View Dependencies' menu item which will show you which tables it relies on. 在SQL Server Management Studio中,如果右键单击存储过程,将有一个“查看依赖项”菜单项,该菜单项将向您显示其依赖的表。 If you need a more programmatic answer, you can extract the dependencies from DMV's (sys.dm_*). 如果您需要更多的编程答案,则可以从DMV(sys.dm_ *)中提取依赖项。
select re.referenced_schema_name + '.' + re.referenced_entity_name as table_name
from sys.dm_sql_referenced_entities('PROC_NAME', 'OBJECT') re
where re.referenced_minor_id = 0;
This also returns a row for any functions the query calls. 这还会为查询调用的所有函数返回一行。 If needed, I'm sure you can filter those out by joining to a DMV that breaks down object types. 如果需要,我确定您可以通过加入细分对象类型的DMV来过滤掉那些对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.