bool doExist = command.ExecuteScalar()!= null由于某种原因不断评估为true

时间:2012-10-22 20:47:33

标签: c# asp.net stored-procedures

  

可能重复:
  ExecuteScalar returns null or DBNull (development or production server)

我有一个存储过程,用于检查预先存在的文件ID是否与项目相关联。如果select语句返回值,则它应该为true并为bool指定“true”。但是当select语句因为它不存在而返回null时,我的代码仍然会使.Execute返回“true”

这是我的存储过程:

ALTER PROCEDURE [dbo].[Events_TaskIDExists] 
@EventID int
AS
BEGIN
    select TaskID from Events where EventID = @EventID
END

这是我背后的代码:

public void hasTaskAssociatedToNote()
{
    String[] Notes = hidSelectedEventIDs.Value.Split(',');
    bool exists = false;
    foreach (var note in Notes)
    {
        var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
        var command = new SqlCommand("Events_TaskIDExists", connection);
        command.Parameters.Add(new SqlParameter("@EventID", SqlDbType.Int));
        command.Parameters["@EventID"].Value = Convert.ToInt32(note.Trim());
        command.CommandType = CommandType.StoredProcedure;
        try
        {
            connection.Open();
            exists = command.ExecuteScalar() != null;//causes true when it returns null......
            var temp = command.ExecuteScalar();//this was just to check something else
            if (exists)
            {
                exhibitWarning.Visible = true;
                Warning1.Text = "There is an existing Task associated 0.";
            }
        }
        catch (SqlException sql)
        {
            lblStatus.Text = "Couldn't connect to the Database - Error";
            lblStatus.ForeColor = System.Drawing.Color.Red;
        }
        catch (Exception ex)
        {
            lblStatus.Text = "An error occured";
            lblStatus.ForeColor = System.Drawing.Color.Red;
        }
        finally
        {
            if (connection.State == ConnectionState.Open)
                connection.Close();
        }
    }
}

2 个答案:

答案 0 :(得分:3)

您的exists变量应设置为:

object result = command.ExecuteScalar();
exists = result != DBNull.Value && result != null;

SqlCommand.ExecuteScalar()的空结果返回DBNull.Value,而不是null。只有空结果集才会返回null

由于您正在根据EventID选择TaskID,我的猜测是您没有将数据库限制为每个事件都需要TaskID,因此您具有空TaskID字段。换句话说,您有包含@EventID的事件记录,但没有关联的任务记录(基于TaskID)。此条件将返回DBNull.Value而不是null

  

返回值 类型:System.Object 第一列的第一列   结果集中的行,或空引用(在Visual Basic中为Nothing)   如果结果集为空。返回最多2033个字符。“ -   MSDN - SqlCommand.ExecuteScalar()

答案 1 :(得分:1)

我可能会霰弹枪,只是

exists = (command.ExecuteScalar() ?? DBNull.Value) != DBNull.Value;

这假设由于某种原因,您的存储过程实际上返回的行的第一列等于DBNull,并且在这种情况下您希望exists == false。一个简短的调试应该证明或证明这一点。