So in C# to use a stored procedure I have code like the following (connection code omitted):
string sql = "GetClientDefaults";
SqlCommand cmd = new SqlCommand(sql);
cmd.CommandType = CommandType.StoredProcedure; //<-- DO I NEED THIS??
cmd.Parameters.AddWithValue("@computerName", computerName);
Where sql is the name of a stored procedure. Now, this code seems to work just fine with and without the commented line.
So, do I need this line? Is there some performance (or other) benefit to setting this? Is there a benefit to NOT setting it or setting it to Text?
According to the tests in this blog post SQL Server will do the parameterization for you, by wrapping your statement in sp_executesql, when you use
CommandType.Text. But when you useCommandType.StoredProcedureyou will parameterize it and thereby saving the database some work. The latter method is faster.Edit:
Setup
I’ve done some tests myself and here are the results.
Create this procedure:
Add a trace to it using SQL Server Profiler.
And then call it using the following code:
Results
In both cases the calls are made using RPC.
Here’s what the trace reveals using
CommandType.Text:And here is the result using
CommandType.StoredProcedure:As you can see the text-call is wrapped in a call to
sp_executesqlso that it is properly parameterized. This will of course create a slight overhead, and thus my previous statement that usingCommandType.StoredProcedureis faster still stands.Another noteworthy thing, and which is also kind of a deal breaker here, is that when I created the procedure without default values I got the following error:
The reason for this is how the call to
sp_executesqlis created, as you can see the parameters are declared and initialized, but they are not used. For the call to work, it should have looked like this:Meaning, when you’re using
CommandType.Textyou have to add the parameters to theCommandTextunless you always want the default values to be used.So, to answer your question
CommandType.StoredProcedureis faster.CommandType.Text, then you’ll have to add the parameter names to the call to the procedure unless you want the default values to be used.