Search code examples
c#.netado.netsqlparameter

Ado.net and Sp's Parameters in cache?


Im reading the code for Microsoft.ApplicationBlocks.Data ( code is here )

But I've notice something strange :

in one of the function ( executeNonQuery) he tries to read Sp's param from cache and if not exists , he put them into the cache ( not asp.net cache - but an internal HashSet)

public static int ExecuteNonQuery(string connectionString, string spName, params SqlParameter[] parameterValues)
    {
        if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
        if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
        // If we receive parameter values, we need to figure out where they go
        if ((parameterValues != null) && (parameterValues.Length > 0))
        {
            // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
            //------------------------------------

            SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

           //------------------------------------
            // Assign the provided values to these parameters based on parameter order
            AssignParameterValues(commandParameters, parameterValues);
            // Call the overload that takes an array of SqlParameters
            return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
        }
        else
        {
            // Otherwise we can just call the SP without params
            return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
        }
    }

Please look at the isolated line.

Why did they do that? How does it help me if I have the params in Cache ? Im gonna send the params anyway from my dal ...( and I must send my params to a SP)...

What am I missing ?


Solution

  • Without the caching, they'd end up calling SqlCommandBuilder.DeriveParameters for each call to ExecuteNonQuery, for which MSDN states:

    DeriveParameters requires an additional call to the database to obtain the information. If the parameter information is known in advance, it is more efficient to populate the parameters collection by setting the information explicitly.

    So it makes sense to cache the retrieved parameter information to avoid these extra calls.

    UPDATE:

    Im gonna send the params anyway from my dal ...( and I must send my params to a SP)...

    Note the int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues) overload -- you may or may not send the parameters.