簡體   English   中英

將SQL條件作為OleDb參數傳遞

[英]Pass a SQL condition as a OleDb parameter

我有以下代碼:

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運算符)的值。

編輯:如何在參數中包含條件?

在簡化構建邏輯表達式的位置之后添加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必須全部為二進制運算符。

數據庫引擎會在用值替換參數之前檢查SQL語句的語法。 因此,諸如“ WHERE @ p1 @ p2 @ p3”之類的東西將無法正確解析。 用字符串表達式替換您的條件,例如

commandtext = parameterName + condition + " @p1"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM