简体   繁体   English

将SQL条件作为OleDb参数传递

[英]Pass a SQL condition as a OleDb parameter

I have following code: 我有以下代码:

Dim executedCmd As OleDb.OleDbCommand = m_dbMgr.GetCommand()
executedCmd.CommandText = "select * from [Parameters] where "
Dim SQLcondition As String = String.Empty
For i As Integer = 0 To ParameterName.Count - 1
 executedCmd.CommandText += "ParameterName = @parametername" + i.ToString() + " and ParameterValue @ParamaterCondition" + i.ToString() + " @ParameterValue" + i.ToString()
 executedCmd.Parameters.AddWithValue("@parametername" + i.ToString(), ParameterName(i))
 executedCmd.Parameters.AddWithValue("@ParameterValue" + i.ToString(), ParameterValue(i))
 executedCmd.Parameters.AddWithValue("@ParamaterCondition" + i.ToString(), Condition(i))
Next

ParameterName , ParameterValue , ParameterCondition all are same length ArrayList , but the code does not work properly. ParameterNameParameterValueParameterCondition都具有相同的长度ArrayList ,但是代码无法正常工作。 I have verified all the variables have values. 我已经验证了所有变量都有值。

When I run the code it reports a syntax error: "missing operations in query expression" 当我运行代码时,它报告语法错误:“查询表达式中缺少操作”

The problem is that ParameterCondition has values like ( '>' , '<' , '=' ,.... some logical SQL operators). 问题在于, ParameterCondition具有类似( '>''<''=' ,...等某些逻辑SQL运算符)的值。

Edit: How can I include conditions in parameters? 编辑:如何在参数中包含条件?

Add 1 = 1 after where to simplify building logical expression. 在简化构建逻辑表达式的位置之后添加1 = 1 Notice that all conditions added by AND logical operator. 请注意,所有条件均由AND逻辑运算符添加。 You can generate parameter name from columns name. 您可以从列名生成参数名。

executedCmd.CommandText = "select * from [Parameters] where 1 = 1"

....
executedCmd.CommandText += " AND " + ParameterName(i) + " " + Condition(i) + " @" + ParameterName(i)
executedCmd.Parameters.AddWithValue("@" + ParameterName(i), ParameterValue(i))

ParameterCondition must all be binary operators. ParameterCondition必须全部为二进制运算符。

The database engine would check the syntax of the SQL statement before it replaces the parameters with values. 数据库引擎会在用值替换参数之前检查SQL语句的语法。 So somethinhg like "WHERE @p1 @p2 @p3" will not be parsed correctly. 因此,诸如“ WHERE @ p1 @ p2 @ p3”之类的东西将无法正确解析。 Replace your condition with a string-expression eg 用字符串表达式替换您的条件,例如

commandtext = parameterName + condition + " @p1"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM