我有一个存储过程,用于检查预先存在的文件 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();
}
}
}