3

我想从列与给定参数匹配的表中进行选择。如果参数为空,我想从表中选择所有记录。下面的相关代码是引发此错误的原因。

    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 中有效地完成此操作而不会出错?

4

4 回答 4

2

您可以通过指定传递给查询的参数类型来避免此错误。所以你需要做的就是:

pjAddress.DbType = DbType.String;
于 2013-11-20T15:51:39.693 回答
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;
}
于 2012-12-30T11:30:00.423 回答
0

您可以将其投射到varchar

SELECT jID FROM Job WHERE jAddress = @jAddress 
    OR cast(@jAddress AS varchar(4000)) IS NULL
于 2014-05-14T08:03:37.010 回答
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),异常消失了。

于 2016-10-21T14:41:08.413 回答