简体   繁体   English

获取SQL语句中使用的所有表的名称

[英]Get name of all the tables used in SQL statement

I have dynamic SQL statement generated using criteria. 我有使用条件生成的动态SQL语句。 This statement involves multiple joins using many tables. 此语句涉及使用许多表的多个连接。 Requirement is to get list of all the tables used in this statement. 要求是获取此语句中使用的所有表的列表。

For example: 例如:

SELECT 
    table1.a, table2.b, ... 
FROM 
    table1 
INNER JOIN 
    table2 ON table1.col1 = table2.col1 
LEFT OUTER JOIN 
    table3 ON table2.col3 = table3.col1

I want to get list of tables used in the above query dynamically like: 我希望动态获取上述查询中使用的表列表,如:

table1,table2,table3.

I am using C# and SQL Server. 我正在使用C#和SQL Server。 I think parsing the string and finding individual tables will be complex. 我认为解析字符串并查找单个表将是复杂的。 Is there any way we can get the list of Tables used in a query from SQL Server itself? 有什么办法可以从SQL Server本身获取查询中使用的表列表吗?

If you have sufficient permission (eg CREATE/DROP VIEW , VIEW DEFINITION ) here's a possible solution that lets SQL Server do most of the work, meaning you won't have to parse the SQL: 如果你有足够的权限(例如CREATE/DROP VIEWVIEW DEFINITION ),这里有一个可以让SQL Server完成大部分工作的解决方案,这意味着你不必解析SQL:

  1. Extend your dynamic SQL so that it creates a (temporary) view with your SELECT query behind it: 扩展动态SQL,以便在其后面创建一个(临时)视图,其中包含SELECT查询:

     CREATE VIEW schema.someRandomUniqueName WITH SCHEMABINDING AS SELECT schema.table1.a, schema.table2.b, ... FROM schema.table1 INNER JOIN schema.table2 ON a.col1=b.col1 LEFT OUTER JOIN schema.table3 ON schema.table2.col3 = schema.table3.col1; 

    Some points to observe: 要注意的一些要点:

    • Make sure to specify WITH SCHEMABINDING . 确保指定WITH SCHEMABINDING
    • Make sure that each table or view name is fully qualified, ie includes the schema name. 确保每个表或视图名称都是完全限定的,即包含模式名称。 This requirements comes from the schema binding option. 此要求来自架构绑定选项。
    • You could create a unique temporary view name eg via String.Format("_{0:N}", Guid.NewGuid()) . 您可以创建一个唯一的临时视图名称,例如通过String.Format("_{0:N}", Guid.NewGuid())
  2. Query sys.dm_sql_referenced_entities for the created view. 查询创建的视图的sys.dm_sql_referenced_entities This will give you the database objects that your SELECT query depends on. 这将为您提供SELECT查询所依赖的数据库对象。 (The following example is untested:) (以下示例未经测试:)

     SELECT referenced_schema_name, referenced_entity_name, referenced_class_desc FROM sys.dm_sql_referenced_entities ('schema.someRandomUniqueName', 'OBJECT'); 
  3. DROP the temporary view; DROP临时视图; it's no longer needed. 它不再需要了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM