Check for duplicate records in a database before INSERT
Posted on 2005-03-02
I have a form with two controls. a textbox called txtName and a button called button1.
The user inputs a name and clicks the button...that is meant to insert that name into the venues database. However, before that I want to check if that name or a name similar exists, and in doing so prompt the user to whether or not there is a similar value or if there is not. If there is a similar value then the user gets the chioce of continuing to insert it or not, and if there is no similar value then it will insert it without any prompts to the user.
I have created a public string called 'duplicate' and then with the myReader this value is filled with nothing (null) if no records are LIKE that value in the Select statement or with the value/record that it is similar to. So I have created an IF statement like so: if(duplicate == null) etc --- but its not working...what is the best solution.
This is the main code:
private void button1_Click(object sender, System.EventArgs e)
string myConnectionString = "Data Source=roman2;Initial Catalog=LPApplication;User Id=sa;Password=test;";
SqlConnection myConnection = new SqlConnection(myConnectionString);
string MSSQL1 = "SELECT * FROM venues where venue_Name LIKE '%"+txtName.Text+"%'";
SqlCommand myCommand = new SqlCommand(MSSQL1);
myCommand.Connection = myConnection;
SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
duplicate = myReader.GetString(1).ToString();
if(duplicate == null)
MessageBox.Show("duplicate value found, do you want to add it anyway?");
MessageBox.Show("no duplicate value found");
//on this assumption i would add insert statement here