views:

166

answers:

6

Solution 1 :

foreach (var item in itemList)
{
   myContext.ExecuteStoreCommand("EXEC MyProc {0};", item); // Insertion
}

or

Solution 2 :

StringBuilder sb = new StringBuilder();
foreach (var item in itemList)
{
   sb.AppendLine(String.Format("EXEC MyProc {0};", item)); // Insertion
}
myContext.ExecuteStoreCommand(sb.ToString());
+5  A: 

both are second one is subject to sql injection, that is for sure

by reading this and this, I agree with kekekela

Fredou
The first isn't since its using a parameterized command.
kekekela
@Justin - the documentation regarding ExecuteStoreCommand indicates that the OP's first statement does in fact generate a parameterized command: http://msdn.microsoft.com/en-us/library/ee358758.aspx
JeremyDWill
@kekekela, I updated my answer
Fredou
+2  A: 

I would guess Solution 2 because there is less I/O between your application and the database. If speed is all you're concerned with, you could check for yourself by debugging with the System.Diagnostics.Stopwatch utility.

Jeremy Wiggins
Test results : Solution 2 is *twice* fast as Solution 1
Patrice Pezillier
Seems like a lot of people suspected it would be. That being said, I'd strongly urge you to consider the others' points about security/sql injection risks. Just because it's the fastest way doesn't necessarily mean it's the best way.
Jeremy Wiggins
+1  A: 

This sounds like an opportunity for a small optimization which is easily tested.

Likely they are very close to the same speed.

codekaizen
Test results : Solution 2 is *twice* fast as Solution 1
Patrice Pezillier
Are we talking 1ms vs. 2ms?
codekaizen
+3  A: 

Solution 2 is faster as its only a single call to myContext.ExecuteStoreCommand so less overhead from method calls through the context object

Bablo
Test results : Solution 2 is *twice* fast as Solution 1
Patrice Pezillier
+1  A: 

The one you haven't mentioned.

Prepare an SqlCommand with the stored procedure's name as the CommandText, the CommandType set to CommandType.StoredProcedure, and the params appropriately added.

Besides the performance gain from not using an ad-hoc query (that'd have to be reparsed each time), you'll also nip most of your current SQL injection issues in the bud.

cHao
+8  A: 

Second is faster (one call to the database instead of multiple), first is safer since it protects against SQL injection.

kekekela