我有一个存储客户记录的表,我想通过这些客户过滤,但我无法将空值放入sproc中。有时值可以为null,我在sql中测试它并且它可以工作,但它不会接受来自c#后面的空值。我尝试使用if语句,结果是一样的。
任何帮助表示赞赏
您可以查看以下代码
SQL
WHERE ( ProcessStatus.ProcessStatusKey = @ProcessStatusKey OR @ProcessStatusKey IS NULL )
AND
( PriorityLevels.PriorityLevelKey = @PriorityLevelKey OR @PriorityLevelKey IS NULL )
AND
( SystemUsers.SystemUserKey = @SystemUserKey OR @SystemUserKey IS NULL )
AND
( CaseHoganData.LoanAccountNumber = @AccountNumber OR @AccountNumber IS NULL )
AND
( ( LTRIM(RTRIM(( ISNULL(Customers.FirstName, '') + ' ' + ISNULL(Customers.LastName, '') ))) ) LIKE '%'
+ @CustomerName + '%'OR @CustomerName IS NULL )
ASP.NET
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("sp_Cases_ViewAll", con))
{
//if (prioritylev == "")
// cmd.Parameters.AddWithValue("@PriorityLevelKey", DBNull.Value);
//else
cmd.Parameters.AddWithValue("@PriorityLevelKey", (string.IsNullOrEmpty(prioritylev) ? (Guid?)null : new Guid(prioritylev)));
cmd.Parameters.AddWithValue("@ProcessStatusKey", (string.IsNullOrEmpty(processkey) ? (Guid?)null : new Guid(processkey)));
cmd.Parameters.AddWithValue("@SystemUserKey", (string.IsNullOrEmpty(systemuser) ? (Guid?)null : new Guid(systemuser)));
cmd.Parameters.AddWithValue("@AccountNumber", accnumber);
cmd.Parameters.AddWithValue("@CustomerName", cusname);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
DataTable dt = new DataTable();
sda.Fill(dt);
grid_Cases.DataSource = dt;
grid_Cases.DataBind();
}
}
}
修改 这对我有用
cmd.Parameters.AddWithValue("@PriorityLevelKey", (string.IsNullOrEmpty(prioritylev) ? (object)DBNull.Value : new Guid(prioritylev)));
答案 0 :(得分:2)
NULL由DBNull
类表示:
https://msdn.microsoft.com/en-us/library/system.dbnull(v=vs.110).aspx
如果没有值,请使用DBNull.Value
。
答案 1 :(得分:2)
您在评论代码的正确路径上#34; DBNull.value",这是您更改的代码:
using (SqlCommand cmd = new SqlCommand("sp_Cases_ViewAll", con))
{
//if (prioritylev == "")
// cmd.Parameters.AddWithValue("@PriorityLevelKey", DBNull.Value);
//else
if (string.IsNullOrEmpty(prioritylev))
{
cmd.Parameters.AddWithValue("@PriorityLevelKey", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("@PriorityLevelKey", new Guid(prioritylev));
}
if(string.IsNullOrEmpty(processkey))
{
cmd.Parameters.AddWithValue("@ProcessStatusKey", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("@ProcessStatusKey", new Guid(processkey));
}
if (string.IsNullOrEmpty(systemuser))
{
cmd.Parameters.AddWithValue("@SystemUserKey", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("@SystemUserKey", new Guid(systemuser));
}
cmd.Parameters.AddWithValue("@AccountNumber", accnumber);
cmd.Parameters.AddWithValue("@CustomerName", cusname);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
DataTable dt = new DataTable();
sda.Fill(dt);
grid_Cases.DataSource = dt;
grid_Cases.DataBind();
}
}
}