4

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
Adriaan
  • 17,741
  • 7
  • 42
  • 75
Houshang.Karami
  • 291
  • 1
  • 3
  • 11
  • You can use `information schema` tables and use that to build your dynamic sql, this way you'll know which columns and tables where used to create sql. – rs. Sep 18 '12 at 19:02
  • I need to pull information out from SQL Query. – Houshang.Karami Sep 18 '12 at 19:39
  • Are you saying you have the TEXT of a SQL query that you'd like to parse - not execute? What about joins, multiple columns, etc. etc? – n8wrl Sep 18 '12 at 19:42
  • So you have a sql query that is dynamic and running on your site? What information do you want to pull? Please post what you have, and what you want to end up with – Andrew Walters Sep 18 '12 at 19:44
  • @Houshang.Karami, i understand you have sql query, what i'm trying to say is try to get information about columns and tables in code which is building your dynamic sql query. – rs. Sep 18 '12 at 19:56
  • For example, I added my script I need something like this: Tables: View1 , Columns name: OrderDate,TotalPayments,... – Houshang.Karami Sep 18 '12 at 20:18
  • related: http://stackoverflow.com/questions/589096/parsing-sql-code-in-c-sharp – user423430 May 08 '14 at 22:58
  • Please see [how to format your [post](/help/formatting). Code goes as code formatting, not a block quote. – Adriaan Nov 16 '22 at 15:23

4 Answers4

4

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!

Maurice Reeves
  • 1,572
  • 13
  • 19
  • I used "Ben Laan" Sql Parser, It sounds great parser,here-> [Ben Laan SQL Parser"](http://code.google.com/p/sqlformat/downloads/detail?name=Laan%20Sql%20Tools%20Src%20v1.1.zip&can=2&q=) but keep in mind for any extra inquiry we need to connect to database directly ,For example when we need to find out which column is belong to which table. – Houshang.Karami Sep 28 '12 at 22:23
  • Excellent! How's it going? Have you been able to accomplish what you set out to do with the parser? – Maurice Reeves Nov 29 '12 at 19:52
1

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.

jTC
  • 1,340
  • 9
  • 17
  • We need to mix this solution with The solution @Maurice has mentioned, If we want to make sure one column is belong to one table ,we need to do some query on sys database. we can extract Table name and column name from given SQL script,But if want to make sure which columns is belong to which table then we need use query on system tables and columns. – Houshang.Karami Sep 24 '12 at 17:15
  • I like this sql parser project,It has been developed by "Ben Laan", I used this parser for what I need, You can Download from [Here](http://code.google.com/p/sqlformat/downloads/detail?name=Laan%20Sql%20Tools%20Src%20v1.1.zip&can=2&q=) – Houshang.Karami Sep 28 '12 at 22:20
0

Elements can be retrieved and edited by using the SQLParser "Carbunql".

https://github.com/mk3008/Carbunql

Sample

Below is an example to get the column name and table name.

using Carbunql;

var sq = new SelectQuery(@"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);");

Console.WriteLine("columns");
sq.SelectClause!.Items.ForEach(item =>
{
    if (string.IsNullOrEmpty(item.Alias))
    {
        //If there is no alias name, return the command
        Console.WriteLine("    " + item.ToOneLineCommand().CommandText);
    }
    else
    {
        Console.WriteLine("    " + item.Alias);
    }
});

Console.WriteLine("table");
var table = sq.FromClause!.Root;
if (string.IsNullOrEmpty(table.Alias))
{
    Console.WriteLine("    " + table.ToOneLineCommand().CommandText);
}
else
{
    Console.WriteLine("    " + table.ToOneLineCommand().CommandText + " as " + table.Alias);
}

Results

columns
    OrderDate
    Email
    SUM(View1.TotalPayments)
table
    dbo.View1 as View1

Remarks

  • The third column is a function and has no alias name, so there is no column name.
  • Getting the table name is cumbersome (because the FROM clause can also specify a subquery).
-1

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()
}
Andrew Walters
  • 4,763
  • 6
  • 35
  • 49
  • 2
    Thanks,but I did not ask about query building.I have already Query,I need to pull information out from SQL Query. – Houshang.Karami Sep 18 '12 at 19:39
  • I am going to use Regular expressions to extract table names and columns names: [link](http://stackoverflow.com/questions/4214045/using-regex-to-extract-table-names-from-a-file-containing-sql-queries) – Houshang.Karami Sep 18 '12 at 20:36