2012-12-30 65 views
3

我想從表中選擇列匹配給定的參數。如果參數爲空,我想從表中選擇所有記錄。下面的相關代碼是拋出這個錯誤的東西。函數的指定參數值無效。 [參數#= 1,函數的名稱(如果知道)= isnull]

private static string _dbJobCreate = 
"CREATE TABLE Job (jID int primary key identity(1,1), jAddress nvarchar(64) not null);"; 

    private static string _dbJobSelect = 
"SELECT jID FROM Job WHERE jAddress = @jAddress OR @jAddress IS NULL"; 

    public static DataTable GetJobs(string jAddress) 
    { 
     SqlCeParameter pjAddress = new SqlCeParameter(); 
     pjAddress.ParameterName = "@jAddress"; 

     if (!string.IsNullOrEmpty(jAddress)) 
     { 
      pjAddress.Value = jAddress; 
     } 
     else 
     { 
      pjAddress.Value = DBNull.Value; 
     } 

     return ExecuteDataTable(_dbJobSelect, pjAddress); 
    } 

例外:The specified argument value for the function is not valid. [ Argument # = 1,Name of function(if known) = isnull ]

我怎樣纔能有效地做到這一點沒有SQLCE錯誤?

+1

有用的討論: http://social.msdn.microsoft.com/Forums/sqlserver/en-US/83821937-3929-4901-a78e-b675cf8a70ca/how-to-send-a-null-value-as -a參數 –

回答

1

我的解決方案是從數據庫中選擇所有行,並在傳入參數時過濾掉.NET中的行。如果有大量作業,這可能會變得很麻煩,但我想我會移動到一個真正的數據庫,如果有的話。

private static string _dbJobSelect = "SELECT jID, jAddress FROM Job"; 

public static DataTable GetJobs(string jAddress) 
{ 
    DataTable dt = ExecuteDataTable(_dbJobSelect); 

    if (!string.IsNullOrEmpty(jAddress)) 
    { 
     DataView dv = dt.DefaultView; 
     dv.RowFilter = string.Format("jAddress = '{0}'", jAddress); 
     dt = dv.ToTable(); 
    } 

    return dt; 
} 
2

您可以通過指定傳遞給查詢的參數類型來避免此錯誤。因此,所有你需要做的是:

pjAddress.DbType = DbType.String; 
+1

對我來說這是完美的解決方案。 – Phil

0

你可以將它轉換爲varchar

SELECT jID FROM Job WHERE jAddress = @jAddress 
    OR cast(@jAddress AS varchar(4000)) IS NULL 
0

我最近就遇到了這個問題,發現我並沒有實際添加的查詢參數IDbCommand。我不知道你ExecuteDataTable方法是什麼樣子,但是按照我的代碼是類似(其中dbIDbConnection實例):

var sql = "SELECT jID FROM Job WHERE jAddress = @jAddress OR @jAddress IS NULL"; 
var cmd = db.CreateCommand(); 
cmd.CommandText = sql; 
var param = cmd.CreateParameter(); 
param.DbType = DbType.String; 
param.ParameterName = "@jAddress"; 
param.Value = string.IsNullOrEmpty(pjAddress) ? DBNull.Value : (object)pjAddress; 
cmd.Parameters.Add(param); // THIS WAS THE STEP I WAS MISSING!!! 
// ... rest of the code to execute the query and load the results ... 

加入cmd.Parameters.Add(param)後,異常消失。