I am inserting values into a database but i get an error, it says the variable name @emp_login has already been declared. How do i resolve this? This is my code

`SqlDataReader readerReference = cmd_Reference.ExecuteReader();
 SqlCommand cmd_Insert = Connexion_Insert.CreateCommand();


string insert = "INSERT INTO EMP_tracking(emp_login, emp_dom_code, emp_domain,emp_surname") 
                 VALUES (@emp_login,@emp_dom_code,@emp_domain,@emp_surname);


        int loginIndex = readerReference.GetOrdinal("a column");
        int DomCodeLoginIndex = readerReference.GetOrdinal("a column");
        int dom_domain = readerReference.GetOrdinal("dom_domaine"); 
        int emp_surname = readerReference.GetOrdinal("a column");


 while (readerReference.Read())//from a different query
      {
cmd_Insert.Parameters.AddWithValue("@emp_login", readerReference.GetInt32(loginIndex));
cmd_Insert.Parameters.AddWithValue("@emp_dom_code", readerReference.GetInt32(DomCodeLoginIndex));
cmd_Insert.Parameters.AddWithValue("@emp_domain", readerReference.GetString(dom_domain));
cmd_Insert.Parameters.AddWithValue("@emp_surname", readerReference.GetString(emp_surname));

cmd_Insert.ExecuteNonQuery();
}
`

Clear your parameters collection when the values change, you're doubling them up and the variable name is a unique key:

while (readerReference.Read())
{
    cmd_Insert.Parameters.Clear();
    cmd_Insert.Parameters.AddWithValue("@emp_login", readerReference.GetInt32(loginIndex));
    cmd_Insert.Parameters.AddWithValue("@emp_dom_code", readerReference.GetInt32(DomCodeLoginIndex));
    cmd_Insert.Parameters.AddWithValue("@emp_domain", readerReference.GetString(dom_domain));
    cmd_Insert.Parameters.AddWithValue("@emp_surname", readerReference.GetString(emp_surname));
    cmd_Insert.ExecuteNonQuery();
}

Unless it was just a typo when you were posting you have a closed the speach marks too early in your SQL statement. It needs to be at the end of the statement instead of after emp_surname.

This article has been dead for over six months. Start a new discussion instead.