【问题标题】:Pass a SQL condition as a OleDb parameter将 SQL 条件作为 OleDb 参数传递
【发布时间】:2013-01-16 11:06:20
【问题描述】:

我有以下代码:

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

ParameterNameParameterValueParameterCondition 都是相同长度的ArrayList,但是代码不能正常工作。我已经验证了所有变量都有值。

当我运行代码时,它会报告语法错误:“查询表达式中缺少操作”

问题在于ParameterCondition 的值类似于('>''<''=',.... 一些逻辑 SQL 运算符)。

编辑:如何在参数中包含条件?

【问题讨论】:

    标签: vb.net ms-access sqlparameter sql-parametrized-query oledbparameter


    【解决方案1】:

    数据库引擎会在将参数替换为值之前检查 SQL 语句的语法。所以像 "WHERE @p1 @p2 @p3" 这样的东西不会被正确解析。 用字符串表达式替换您的条件,例如

    commandtext = parameterName + condition + " @p1"
    

    【讨论】:

    • 如何参数化该条件?有办法吗?
    【解决方案2】:

    在 where 之后添加 1 = 1 以简化构建逻辑表达式。请注意,AND 逻辑运算符添加的所有条件。您可以从列名称生成参数名称。

    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 必须都是二元运算符。

    【讨论】:

      猜你喜欢
      • 2011-11-02
      • 1970-01-01
      • 2011-03-20
      • 2017-07-21
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 2012-06-23
      • 2013-06-22
      相关资源
      最近更新 更多