0

I need to declare parameter once and then use it several times with Insert query like:

SqlCommand mainCMD = new SqlCommand("", conn);
for (int i = 0; i < 5; i++)
{
    mainCMD.CommandText += "INSERT INTO Country (name) VALUES (@cntr)";
    mainCMD.Parameters.AddWithValue("@cntr", "Country" + i);
}
mainCMD.ExecuteNonQuery();

How can i do it?

2
  • Looks like you are doing a lot of thing wrong. First of all, you adding mainCMD.CommandText 5 times to itself. Commented Dec 4, 2013 at 13:33
  • Yes, that's just non working example - just wanted to show what I'd like to reach. Commented Dec 4, 2013 at 13:36

3 Answers 3

3

You should change name of parameter

SqlCommand mainCMD = new SqlCommand("", conn);
for (int i = 0; i < 5; i++)
{
   mainCMD.CommandText += 
       String.Format(" INSERT INTO Country (name) VALUES (@cntr{0})", i);
   mainCMD.Parameters.AddWithValue("@cntr" + i, "Country" + i);
}

Also it will be more efficient to build command text separately:

int countriesCount = 5;

StringBuilder builder = new StringBuilder();      
for(int i = 0; i < countriesCount; i++)
    builder.AppendFormat("INSERT INTO Country (name) VALUES (@cntr{0}) ", i);

var cmd = new SqlCommand(builder.ToString(), conn);
for (int i = 0; i < countriesCount; i++)
    cmd.Parameters.AddWithValue("@cntr" + i, "Country" + i);
Sign up to request clarification or add additional context in comments.

1 Comment

I like the second example, I'd probably only use one for loop though
2

Just use mainCMD.Parameters.clear() at the end of the loop

SqlCommand mainCMD = new SqlCommand("", conn);
for (int i = 0; i < 5; i++)
{
    mainCMD.CommandText += "INSERT INTO Country (name) VALUES (@cntr)";
    mainCMD.Parameters.AddWithValue("@cntr", "Country" + i);
    mainCMD.ExecuteNonQuery();
    mainCMD.Parameters.clear();

}

Comments

1

Build your command and parameter ONCE, then just change the parameter value IN the loop

SqlCommand mainCMD = new SqlCommand( " INSERT INTO Country (name) VALUES (@parmCountry)", conn);
// just to prime the parameter with proper data type string expectation
mainCMD.Parameters.AddWithValue("@parmCountry", "test country");
for (int i = 0; i < 5; i++)
{
   // change ONLY the parameter, then execute it
   mainCMD.Parameters[0].Value = "Country" + i.ToString();
   mainCMD.ExecuteNonQuery();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.