Parsing SQL Query and pull out column name and Table name

橙三吉。 提交于 2019-12-22 10:18:59

问题


I have a Query Script like this:

SELECT View1.OrderDate,View1.Email,SUM(View1.TotalPayments) FROM dbo.View1 WHERE (View1.OrderStatus = 'Completed') GROUP BY View1.OrderDate,View1.Email HAVING (SUM(View1.TotalPayments) > 75);

Is there any approach that we can pull some key information out from SQL query? such as table name and column name ,I have 2 question:

  1. I did search I found some parser such as ANTLR , but I could not find documentation that explain the using of this parser in C# language.
  2. Is there any way we can use Entity Frame Work to parsing sql query? My queries are fully dynamic and they are created at run time

回答1:


I think the best answer is going to be to use the Irony parser: http://irony.codeplex.com/

Hanselman has a great link to how to use it to parse SQL: http://www.hanselman.com/blog/TheWeeklySourceCode59AnOpenSourceTreasureIronyNETLanguageImplementationKit.aspx

I hope this helps, and best of luck!




回答2:


You could use some of the system tables to get at the information you are looking for.

select p.name ParentTable, r.name ReferencedTable, k.name KeyName
from sys.foreign_keys k
join sys.tables p on k.parent_object_id = p.object_id
join sys.tables r on k.referenced_object_id = r.object_id

Depending on how consistent your database is you can make assumptions to what the Key Name would be. So if the reference table was [User] you could assume that you are referencing the UserId, if you have multiple keys in your table this wouldn't be the answer you are looking for.




回答3:


You can build dynamic queries in entity framework like this

If(case1)
{
    var query = db.x.where(x => x).toList();
}
else
{
   var query = db.x.where(y => y).toList()
}


来源:https://stackoverflow.com/questions/12483173/parsing-sql-query-and-pull-out-column-name-and-table-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!