Thursday, March 22, 2012

looping sql insert command

I have a webpage where i ask a user to input a value in a textbox which is than saved in a sql database. However there are no fix number of values a user would want to insert, so I let them dynamically create the textboxes by asking a simple question - "How many values do you wish to input?". My problem is when i try to call the sqlinsertcommand multiple times through a loop, it only save the firt value and then throws in an error "System.Data.SqlClient.SqlException: Procedure or function Activity_Insert has too many arguments specified.". Here is what my insert command function looks like (which i repetadely call through a loop). The insert command is a stored proceudre called.

PrivateSub saveActivity()

Try

Me.SqlConnection2.Open()

Me.SqlInsertActivity.Parameters.Add(New System.Data.SqlClient.SqlParameter("@dotnet.itags.org.RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue,False,CType(0,Byte),CType(0,Byte), "", System.Data.DataRowVersion.Current,Nothing))
Me.SqlInsertActivity.Parameters.Add(New System.Data.SqlClient.SqlParameter("@dotnet.itags.org.Isotope", System.Data.SqlDbType.Int, 4)).Value = save_tb.Text

Me.SqlInsertActivity.ExecuteNonQuery()
Catch exAs Exception
Dim errorisAsString
lblerror.Text = ex.ToString()
Finally
Me.SqlConnection2.Close()
EndTry

You say you're calling saveActivity multiple times? From looking at the code, your command (SqlInsertActivity) is being created somewhere else, and "lives" across calls to saveActivity, but you are adding the parameters to it on each iteration. The result is that you keep adding parameters to the existing list on each iteration.
Instead, try adding the parameters when you create the command, but with no values, then just set the values of the parameters in saveActivity.



Add this code after Me.SqlInsertActivity.ExecuteNonQuery()
Me.SqlInsertActivity.Parameters.Clear();
Give a try and let me know if it works

Hi Sam,
your method sure did work . I am very very thankful to you and the forum for the help.
Zubin

0 comments:

Post a Comment