Possible Duplicate:
Pros and Cons of using SqlCommand Prepare in C#?
This is what MSDN says about SqlCommand.Prepare()
:
Creates a prepared version of the command on an instance of SQL Server.
Can anybody provide more insight as to what that means and when it should be used?
The Prepare
method is actually on DbCommand
, which all classes which derive from it will pick up.
What it does is specific to the database provider that the DbCommand
is for. However, it's safe to say (although not an absolute rule) that in most places, if the command is a stored procedure, it will produce a no op (it is documented as such for the override of Prepare
on SqlCommand
), as stored procedures typically have their query plans optimized because of prior calls, explicit calls to optimize, or on creation (again, depending on the underlying database).
However, if you are not using a stored procedure, but rather a parameterized query generated on-the-fly, then this call will give the underlying database the opportunity to generate an optimized version of the query.
You would typically do this when you know you are going to execute the command multiple times within a short amount of time (it depends, really, on the database, and how long the query plans are cached).
It should be stated that SQL Server (as of 2005, IIRC) caches parameterized query plans depending on usage after the first execution (I think the cache is a time-degraded cache which resets or has its rate of decay slowed on subsequent uses), so if you are going to make multiple calls with the same parameterized query, then you might not gain much with a call to Prepare
other than moving the query preparation work upfront (which might be a benefit as well, depending on what the work is you have to perform).