Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 8, 2012 15:58
Show Gist options
  • Select an option

  • Save davybrion/3676387 to your computer and use it in GitHub Desktop.

Select an option

Save davybrion/3676387 to your computer and use it in GitHub Desktop.
code snippets for "Batching SqlCommand Queries" post
public class SelectCommandCombiner
{
private readonly List<SqlCommand> commands = new List<SqlCommand>();
public SelectCommandCombiner() : this(new SqlCommand[0]) { }
public SelectCommandCombiner(IEnumerable<SqlCommand> commandsToCombine)
{
commands = new List<SqlCommand>();
if (commandsToCombine != null)
{
AddCommands(commandsToCombine);
}
}
public void AddCommands(IEnumerable<SqlCommand> commandsToAdd)
{
commands.AddRange(commandsToAdd);
}
public SqlCommand CreateCombinedCommand()
{
var combinedCommand = new SqlCommand();
var combinedCommandText = new StringBuilder();
var queryIndex = 0;
foreach (var currentCommand in commands)
{
var currentCommandText = new StringBuilder(currentCommand.CommandText);
CreateUniqueParameters(currentCommand, currentCommandText, combinedCommand, queryIndex);
combinedCommandText.Append(currentCommandText + ";" + System.Environment.NewLine);
queryIndex++;
}
combinedCommand.CommandText = combinedCommandText.ToString();
return combinedCommand;
}
private static void CreateUniqueParameters(SqlCommand currentCommand, StringBuilder currentCommandText,
SqlCommand combinedCommand, int queryIndex)
{
foreach (SqlParameter parameter in currentCommand.Parameters)
{
var clonedParameter = CloneParameter(parameter);
MakeParameterNameUnique(queryIndex, clonedParameter);
combinedCommand.Parameters.Add(clonedParameter);
ReplaceOldNameWithNewName(parameter, clonedParameter, currentCommandText);
}
}
private static SqlParameter CloneParameter(ICloneable parameter)
{
return (SqlParameter)parameter.Clone();
}
private static void MakeParameterNameUnique(int queryIndex, SqlParameter clonedParameter)
{
var modifiedParameterName = queryIndex + "_" + clonedParameter.ParameterName;
clonedParameter.ParameterName = modifiedParameterName;
}
private static void ReplaceOldNameWithNewName(SqlParameter parameter, SqlParameter clonedParameter,
StringBuilder currentCommandText)
{
currentCommandText.Replace("@" + parameter.ParameterName, "@" + clonedParameter.ParameterName);
}
}
var reader = combinedCommand.ExecuteReader();
do
{
while (reader.Read())
{
// do something with the values in the current row
}
}
while (reader.NextResult()); // this moves to the next result set
reader.Close();
var adapter = new SqlDataAdapter(combinedCommand);
var dataSet = new DataSet();
adapter.Fill(dataSet);
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
// do something with the values
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment