Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to coalesce/tokenize a SQL Command

Tags:

c#

.net

vb.net

I would like to break a "SELECT" SQL statement into its logical components. i.e. I would like to create an object like "SelectSqlStatement" which has a property called "Table", "Where", "OrderBy", etc. The reason I want to do it is that I don't want to manipulate a string but rather manipulate an object and serialize it back to a string.

Before I write one for .NET, I was wondering if there was one available. I did a search but didn't see anything.

like image 233
Denis Avatar asked Oct 06 '26 22:10

Denis


2 Answers

You can use the scriptdom parser of sql server for that. Its in the Microsoft.SqlServer.TransactSql.ScriptDom.dll and give you an ast of TSqlFragment's that builds up the tsql query.

static void Main(string[] args)
{
    bool initialQuotedIdentifiers = false;
    TSqlParser parser = new TSql110Parser(initialQuotedIdentifiers);

    StreamReader sr = new StreamReader(@".\test.sql");
    IList<ParseError> errors;
    TSqlFragment fragment = parser.Parse(sr, out errors)

    //do stuff with the fragment

    //Generate tsql from the fragment
    StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
    Sql110ScriptGenerator scriptGen = new Sql110ScriptGenerator();
    scriptGen.GenerateScript(fragment, sw);
}
like image 131
Rolf Huisman Avatar answered Oct 09 '26 12:10

Rolf Huisman


  • LINQ
  • Entity Framework
  • nHibernate
    • nHibernate as the solution for .NET 2.0 ORM

Just to name a few. What you are looking for is an ORM

*All links are what I could quickly find for VB.

like image 20
Justin Pihony Avatar answered Oct 09 '26 12:10

Justin Pihony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!