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();
}

Thanks deception it works.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.