C# - Inserting multiple rows using a stored procedure

后端 未结 5 1635
青春惊慌失措
青春惊慌失措 2021-02-15 14:17

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:25

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

提交回复
热议问题