计算存储为字符串的表达式
我想在数据库中存储一个布尔表达式,并对其求值。没有必要存储完整的表达式树,一个字符串可能就可以做到。
我想象了这样的方案: Criteria (expression_to_evaluate, value_to_return)
例如,假设我有一个与年龄在 20 到 40 岁之间的人匹配的表达式:
(var >= 20 AND var <= 40)
var
将会有替换为相关人员的年龄,如果有匹配,则应返回该行。如果不匹配,则应考虑下一行,评估该表达式,依此类推。
还可以有更复杂的表达式,例如: ((var >= 20 AND var <= 40) OR (var < 10))
甚至可能有两个变量: ((var1 <= 10) AND (var2 >= 10 OR var1 == 20))
这应该在 SQL (SQL Server 2005/2008) 或 C# 中完成。应返回匹配行的值并在 C# 中进一步处理。
这可能吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行
|EXEC
允许您首先构建 T-SQL 字符串,然后执行它。您可以执行逻辑,首先根据变量构建字符串,然后简单地EXEC
它。同样,您可以在 C# 中执行相同的操作,并使用
ExecuteNonQuery()
或ExecuteReader()
。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 simplyEXEC
it.Along the same lines, you can do the same in C#, and execute the T-SQL using
ExecuteNonQuery()
orExecuteReader()
.使用 System.Linq.Dynamic 内容,与普通的 linq-to-sql 一起深深隐藏在 Visual Studio 代码示例中。指定的属性名称将映射到生成的实体类。
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.