If I prepare the same statement twice for sqlserver - will sqlserver prepare it twice or use the first one?

StackOverflow https://stackoverflow.com/questions/21165250

  •  28-09-2022
  •  | 
  •  

Question

Can anybody tell me what SQL Server does if I prepare the same statement twice.

Does it prepare it again or use the "compilation" from the first prepare?

I have the following function that may get called several times:

function prepareStoredProcedure (spName, arrParams)
{
var cmd = Server.CreateObject("ADODB.Command")
cmd.CommandType = adCmdStoredProc;
cmd.ActiveConnection = Connection;
cmd.CommandText = spName;
cmd.Prepared = true;

var params = [];
for (var i=0; i<arrParams.length; i++)
{
if (arrParams[i].Size)
  params.push(cmd.CreateParameter(arrParams[i].Name, arrParams[i].Type, 1, arrParams[i].Size)); // Name, Type, Direction, Size
else
  params.push(cmd.CreateParameter(arrParams[i].Name, arrParams[i].Type, 1));

cmd.Parameters.Append(params[i]);
}

return cmd;
}

I'm using sql server 2008, 2008 R2 and 2012

Was it helpful?

Solution

It will use the first compiled version.

There are other nuances in terms of re-execution. For example, depending on the stored procedure, SQL Server might (and hopefully will be able to use) the cached query plan. But if there is dynamic SQL, certain types of logic, or large data changes (among other things), then the DB engine will need to rebuild the query plan.

But stored procedure 'compilation' is done at the time of creation. Unless you specify for it to do otherwise (see here) then it will not recompile.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top