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

标签 c# asp.net stored-procedures

Possible Duplicate:
ExecuteScalar returns null or DBNull (development or production server)

我有一个存储过程,用于检查预先存在的文件 ID 是否与某个项目关联。如果 select 语句返回值,则该值应该为 true,并将“true”分配给 bool。但是,当 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();
        }
    }
}

最佳答案

您的 exists 变量应设置为:

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

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

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

"Return Value Type: System.Object The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters." - MSDN - SqlCommand.ExecuteScalar()

关于c# - bool doesExist = command.ExecuteScalar() != null 由于某种原因不断评估为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13019600/

相关文章:

sql - 如何从一个存储的proc中从SYS_REFCURSOR中获取数据,并在另一个过程中使用它?

sql - MySQL程序?功能?

C# - 通过串行端口从设备获取所有数据并检测控制字符(ACK、SOH、...)

c# - 如何使用 Enum 为数据验证提供描述性状态

sql-server - 存储过程中的经典 ADO 和表值参数

c# - 接受泰米尔语字体的 Web 应用程序

asp.net - 在 ASP.NET 中修改服务器端的 html 输出

c# - 如何调用 UpdateSource() 以在 DataGrid 上进行显式绑定(bind)?

不同应用程序(WPF 和 Unity)中的 C# 结构序列化返回不同大小的字节数组

c# - 无法将字符串从托管 c# 传递到非托管 c