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/