expression tree to sql statement

c# expression-trees

Question

I'm wondering how one would translate a sql string to an expression tree. Currently, in Linq to SQL, the expression tree is translated to a sql statement. How does on go the other way? How would you translate

select * from books where bookname like '%The%' and year > 2008 

into an expression tree in c#?

1
7
5/14/2010 11:31:57 PM

Popular Answer

I don't know if there's an easier way, but I wrote a lexer and parser for SQL expressions into a custom Abstract Syntax Tree (as I didn't know about .net's Expression Trees at the time) and I didn't really enjoy parsing SQL.

The syntax just is not very parse friendly, as order is different depending on context (e.g. the not in NOT IN vs. IS NOT), tokens are overloaded (the parenthesis for overriding the default operator precedence vs. parentheses for creating a list as in WHERE x IN (1, 2)) and so forth.

Obviously using a parser generator rather than doing your own lexing and parsing would make things easier, but I don't know if there's anything more specific to SQL.

So, writing your own is definitely possible, albeit tedious.

0
7/12/2012 11:49:45 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow