简体   繁体   中英

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. 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).

Edit: How can I include conditions in parameters?

Add 1 = 1 after where to simplify building logical expression. Notice that all conditions added by AND logical operator. 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.

The database engine would check the syntax of the SQL statement before it replaces the parameters with values. So somethinhg like "WHERE @p1 @p2 @p3" will not be parsed correctly. Replace your condition with a string-expression eg

commandtext = parameterName + condition + " @p1"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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