Sunday, November 30, 2014

execute a stored procedure in a loop

Both alternatives are viable. Calling the SP from your code is trivial: Just write a loop that iterates through the List and invokes the procedure on each iteration. The (simplified) code would be similar to this:



SqlCommand cmd = new SqlCommand("myStoredProc", myConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@myParameter", SqlDbType.NVarChar, 50);
myConnection.Open();
foreach (string s in myList)
{
cmd.Parameters[0].Value = s;
cmd.ExecuteNonQuery();
}
myConnection.Close();

The drawback to this approach is performance: If you have to pass lots and lots of strings, this will involve many invocations of the SP, which will be less than optimal.


There are many approaches to passing a list of values to an SP. You could encapsulate them in XML and use an XML parameter for the SP, which can then be parsed within the SP. Or you can pass a string that concatenates all the values with an interspersed separator such as a comma, and then process it with dynamic SQL. But, if you have SQL Server 2008 or above, the best way is to use a TABLE parameter. In your client code, insert the List items into a DataTable, and then pass the DataTable to the SP in its TABLE parameter. The SP can then process the table as a set, such as using an "insert into myTable select from theparameter", which would let you insert all of the rows without looping.


No comments:

Post a Comment