1

I've got a DataTable which has a number of records.

I've tried the following code for iterating through the DataTable and inserting into the database, but I am receiving an error message saying that the parameters have not been declared:

       using (SqlCommand command = new SqlCommand(("My insert statement"), connection))
                    {

                        SqlParameter param1 = new SqlParameter();
                        SqlParameter param2 = new SqlParameter();

                        param1.ParameterName = "@ProductID";
                        param2.ParameterName = "@ID";

                        foreach (DataRow row in table.Rows)
                        {
                            param1.Value = row[0].ToString();
                            param2.Value = row[1].ToString();

                            command.ExecuteNonQuery();
                        }

                    }

Any ideas? Please do not suggest stored procedures - I'd like to do this through this method or something similar.

1
  • 1
    I don't see you passing the parameters to the command object in this code. Commented Nov 12, 2011 at 19:02

3 Answers 3

1

You need to add your parameters to the command.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx

Caution though

The way you have your code if you put the add in the foreach your first execute will work and then the next will fail with an error message stating that you have a variable named @ProductID / @ID already.

You need to clear the parameters each time.

See this for an example.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - this was my problem :)
1

Check out SqlBulkCopy, it will allow you to pass in your Datatable straight to the database. Link

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
    bulkCopy.DestinationTableName = "dbo.TableYouWantToInsertTheRowsTo";

    try
    {
         // Write from the source to the destination.
         bulkCopy.WriteToServer(newProductsDataTable);
    }
    catch (Exception ex)
    {
         Console.WriteLine(ex.Message);
    }
}

Comments

0

If you are using SQL2008 than entire List of object/datatable can be passed as parameter to store procedure. In this case you need to declare same class in sql also.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.