C# - Inserting multiple rows using a stored procedure

后端 未结 5 1487
清酒与你
清酒与你 2021-02-15 14:05

I have a list of objects, this list contains about 4 million objects. there is a stored proc that takes objects attributes as params , make some lookups and insert them into tab

5条回答
  •  清酒与你
    2021-02-15 14:36

    It's never going to be ideal to insert four million records from C#, but a better way to do it is to build the command text up in code so you can do it in chunks.

    This is hardly bulletproof, and it doesn't illustrate how to incorporate lookups (as you've mentioned you need), but the basic idea is:

    // You'd modify this to chunk it out - only testing can tell you the right
    // number - perhaps 100 at a time.
    
    for(int i=0; i < items.length; i++) {
    
        // e.g., 'insert dbo.Customer values(@firstName1, @lastName1)'
        string newStatement = string.Format(
            "insert dbo.Customer values(@firstName{0}, @lastName{0})", i);
        command.CommandText += newStatement;
    
        command.Parameters.Add("@firstName" + i, items[i].FirstName);
        command.Parameters.Add("@lastName" + i, items[i].LastName);
    }
    // ...
    command.ExecuteNonQuery();
    

提交回复
热议问题