我想从列中匹配给定参数的表中进行选择。如果参数为null,我想从表中选择所有记录。下面的相关代码会引发此错误。
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中有效地完成此操作?
答案 0 :(得分:2)
您可以通过指定传递给查询的参数类型来避免此错误。所以你需要做的就是:
pjAddress.DbType = DbType.String;
答案 1 :(得分: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 :(得分:0)
您可以将其投放到varchar
SELECT jID FROM Job WHERE jAddress = @jAddress
OR cast(@jAddress AS varchar(4000)) IS NULL
答案 3 :(得分:0)
我最近遇到了这个问题,发现我实际上没有将查询参数添加到IDbCommand
。我不确定您的ExecuteDataTable
方法是什么样的,但我的代码类似于以下内容(其中db
是IDbConnection
个实例):
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)
后,异常消失了。