Execute a stored procedure multiple times in the same connection

3.2k views Asked by At

Is this even possible with the command object? I need to change this piece or code to run a proc (sp_insertRecord) multiple times for the set of Parameters (created from the Records List object) in the same connection based. Right now it creates comma separated insert script and executes all at once. Team Leader suggested call the stored procedure and parameters with semicolon separating them at once. How do I do this as the Leader adviced instead of calling everything in the loop that executes for each set of the Records object. Thats the only way I can think.

sql.Append(first.GetSqlInsertStatment());
Records.ForEach(a => sql.Append(CreateInsertValuesCommaSeperated()));

sql.Length -= 2;
using (var connection = GetDbConnection())
using (var cmd = connection.CreateCommand())
{     
    cmd.Connection.ChangeDatabase(schema);
    cmd.CommandText = sql.ToString();
    cmd.ExecuteNonQuery();          
}
1

There are 1 answers

6
Parrish Husband On

This uses the same DbConnection, and DbCommand, but iterates through the records:

using (var connection = GetDbConnection())
using (var cmd = connection.CreateCommand())
{     
    cmd.Connection.ChangeDatabase(schema);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "sp_insertRecord";

    cmd.Parameters.Add("@stringVal", SqlDbType.NVarChar);
    cmd.Parameters.Add("@numVal", SqlDbType.Int);
    cmd.Parameters.Add("@dateVal", SqlDbType.DateTime);

    int insertCount = 0;
    foreach(var record in records)
    {
        cmd.Parameters["@stringVal"].Value = record["stringVal"];
        cmd.Parameters["@numVal"].Value = record["numVal"];
        cmd.Parameters["@dateVal"].Value = record["dateVal"];

        insertCount += cmd.ExecuteNonQuery();
    }        
}

I'm not sure what class type your records are, but you get the idea. If you have the ability to use SQLBulkCopy and not stored procedures, that's likely the fastest option.