0

I want to check if the staff member does not already exists in the database before I add. In the below code, the if(dr.HasRows) statement executes even if the select statement returned no results. I don't know what I'm doing wrong. Please help.

using (SqlCommand sqlCommand = new SqlCommand("select COUNT(*) from 
       [CLIENT_PROCESSING_CLIENT_INFORMATION] where Client_NB_Number 
       = @StaffNo", sqlConn))
{
    sqlCommand.Parameters.AddWithValue("@StaffNo", strStaffNumber);
    SqlDataReader dr = sqlCommand.ExecuteReader();
    string strMsg = "";
    if(dr.HasRows)
    {
       strMsg = "NB" + strStaffNumber + " already exists.";
       String Script = "<Script language=\"javascript\">alert('" + strMsg + " ') 
          </script>";
       if (!Page.ClientScript.IsClientScriptBlockRegistered("OpenAlert"))
          Page.ClientScript.RegisterClientScriptBlock(this.GetType(), 
                "OpenAlert", Script);
       return;
     }
}
4

2 回答 2

2

您正在返回Count(*),它总是会返回带有结果的单行。

您在这里不需要阅读器,您可以使用ExecuteScalar默认情况下从第一行返回第一列,例如

if ((int)sqlCommand.ExecuteScalar() > 0)
{
    strMsg = "NB" + strStaffNumber + " already exists.";
    String Script = "<Script language=\"javascript\">alert('" + strMsg + " ') </script>";
    if (!Page.ClientScript.IsClientScriptBlockRegistered("OpenAlert"))
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OpenAlert", Script);
    return;
}
于 2013-11-04T12:19:27.683 回答
2

SELECT COUNT(*) 将始终返回 1 个结果,这意味着行数。
您也可以使用 ExecuteScalar 而不是 ExecuteReader 来获取此值。

于 2013-11-04T12:19:31.960 回答