The code below is supposed to iterate through a list of components and insert them for a specific bill of materials. The code executes the loop once, and then sends out an error message,
The variable name '@product' has already been declared. Variable names must be unqiue within a query batch or stored procedure.
Im not sure the best way to change this or why this is being thrown. Any thoughts?
Would I just have to move the foreach outside of the second using
statement?
public static void insert_rework(string product, List<string> component_list, string sn, DateTime today, string connectionString)
{
string sql =
@"INSERT INTO table (
Product,
Component,
Serial_Num,
Cur_Date)
VALUES (
@product,
@component,
@sn,
@date)";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
foreach (string component in component_list)
{
command.Parameters.AddWithValue("@product", product);
command.Parameters.AddWithValue("@component", component);
command.Parameters.AddWithValue("@sn", sn);
command.Parameters.AddWithValue("@date", today);
try
{
command.ExecuteNonQuery();
}
catch (SqlException sq)
{
Console.WriteLine(sq.Message);
}
}
}
}