简体   繁体   中英

Execute a stored procedure multiple times in the same connection

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();          
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM