Wednesday, March 21, 2012

hi, i need help on SQL, thanks


I'm doing a shopping cart using SQL Express and Visual Studio Web Developer on C#, ASP.NET

I recieved error when adding a order:

The variable name '@.oid' has already been declared. Variable names must be unique within a query batch or stored procedure.


The codes are:
comm = new SqlCommand("SELECT IDENT_CURRENT('Orders') as NewOrderID ");

comm.Connection = conn;
comm.Transaction = myTrans;

OrderID = Convert.ToInt32(comm.ExecuteScalar());

foreach (CartItem i in o.ItemList)
{
comm.CommandText = "INSERT INTO OrderDetail(OrderID, ProductID,Quantity, UnitPrice)VALUES (@.oid, @.pid, @.qty, @.price)";

comm.Parameters.AddWithValue("@.oid", OrderID);
comm.Parameters.AddWithValue("@.pid", i.ProductID);
comm.Parameters.AddWithValue("@.qty", i.Quantity);
comm.Parameters.AddWithValue("@.price", i.UnitPrice);
comm.Connection = conn;
comm.Transaction = myTrans;
comm.ExecuteNonQuery();
}

It seems that i can't add records into database with multiple loop.

Thanks in advance.

Well you want to only call once the insert for multiple items, that will optimize the code a little bit more.

Use TableAdapters, On the project right click and select Add New Item, select a DataSet and create a method to add multiple items!

|||

Try to clear parameters after each insert.

Add this to the end of your code block:

...........

comm.ExecuteNonQuery();

comm.Parameters.Clear();

}

|||

Thanksalbertpascual,

I'm not sure about using a TableAdapter, but does declaring the parameters outside the loop works?

I tried adding a dataset but with my limited 1month knowledge, I don't know how to complete the wizard or codes for the dataset.

if changing my existing codes works, it will be great.

thanks again,

|||

Hey, thanks alot Limno!!

but adding this sweet and simple "comm.Parameters.Clear();" it works..

thanks!!

No comments:

Post a Comment