views:

110

answers:

2

I want to store a boolean expression in a database, and evaluate it. It’s not necessary to store the complete expression tree, a string probably do it.

I imagined a scheme like this: Criteria (expression_to_evaluate, value_to_return)

For example, let’s say that I have an expression that matches people with age between 20 and 40:

(var >= 20 AND var <= 40)

var would have to be substituted with the age of the person in question, and if there’s a match it should return that row. If it doesn’t match, the next row should be considered, evaluating that expression, and so on.

There can be more complicated expressions such as: ((var >= 20 AND var <= 40) OR (var < 10))

Maybe even with two variables: ((var1 <= 10) AND (var2 >= 10 OR var1 == 20))

This should be done in either SQL (SQL Server 2005/2008) or C#. The value of the matching row, should be returned and further processed in C#.

Is this even possible?

+1  A: 

EXECUTE | EXEC allows you to first build a string of T-SQL and then execute it. You could perform logic to first build your string depending on your variables, then simply EXEC it.

Along the same lines, you can do the same in C#, and execute the T-SQL using ExecuteNonQuery() or ExecuteReader().

Codesleuth
I didn't even think of that. It actually sounds like a solution, but I'm wondering how I can determine how many variables are required. I somehow have to map this from C# (the parameters to pass in) to the expression to be evaluated. Any ideas?
Tommy Jakobsen
That can get quite complex. There's a Code Project article where someone has explored this: http://www.codeproject.com/KB/database/Building_Dynamic_SQL.aspx
Codesleuth
A: 

Use the System.Linq.Dynamic stuff, which is deeply hidden in the Visual Studio code samples, together with the normal linq-to-sql. The specified property names are mapped against the generated entity class.

myContext.MyTable.Where("Property > 20 && Property < 40").ToList();
Simon Svensson
I've never heard about Linq.Dynamic, which sounds pretty useful in this case. I might be able to use it. Do you know anything about how they are evaluated? Is it done by the DBMS? What about sql injection attacks?
Tommy Jakobsen
It's a parser that converts those strings into normal expression trees. It's not database specific, and it evaluates against properties on the queried object. There's no database involved by Dynamic Linq, it just creates expression trees that are passed to the underlying IQueryable<T> implementation, which could be linq-to-sql. It's the responsibility of the IQueryable<T> implementation to avoid sql injections.
Simon Svensson