I have a method to check if a name already exists in DB or not. The way I am doing it now is first I am getting the company name by company id then I am checking the name with the name I am receiving from the UI
as a param.
Now the current code is tremendous, is there any easiest way to do it or I can improve the current code.
public BaseResponse CheckDupliateCompany(string companyName, string companyId)
{
BaseResponse response = new BaseResponse();
string existingCompanyName = null;
using (SqlConnection con = new SqlConnection(connectionString))
{
if (companyId != null)
{
string sqlQuery = "SELECT * FROM CompanyInformation where CompanyID= " + companyId;
SqlCommand cmd = new SqlCommand(sqlQuery, con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
existingCompanyName = rdr["CompanyName"].ToString();
}
if (string.Equals(existingCompanyName, companyName))
{
response.Status = (int)Status.Failed;
} else
{
response.Status = (int)Status.Success;
}
con.Close();
}
else
{
string sqlQuery = "SELECT * FROM CompanyInformation where CompanyName= '" + companyName + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
response.Status = (int)Status.Failed;
}
con.Close();
}
}
return response;
}