简体   繁体   中英

Parameterized Multi-Row Insert into SQL Server

I'm facing a situation where I need to insert as many as 17,000 rows into a SQL Server database all at once. I've come up with two ways to do that, but I'm getting tripped up over query parameterization in C#.

One caveat: I'm worried about performance, but not to the exclusion of all else -- if the operation I'm doing takes 8 minutes, then whether I add another 5 seconds vs. 10 seconds for the data insert doesn't really matter. If the data insert takes an additional 10 minutes on top of the initial operation, that's a big deal.

Option 1: Multi-Row Insert (chunked)

The first option is to do a simple multi-row insert:

INSERT INTO MyTable (FirstName, LastName, Age)
   VALUES
      ('Bob', 'Smith', 24),
      ('Sally', 'Jones', 32),
      ('Jennifer', 'Johnson', 23)

I would build up several of these queries via something like this. (I'm writing this off of the top of my head, so there's almost certainly a bug in here. That's not important -- it's meant to illustrate my point):

var queriesNeeded = people.Count / 250;

for (int i = 0; i < queriesNeeded; i++)
{
   var records = people.Skip(i * 250).Take(250);
   BuildAndExecuteQuery(records);
}

// Handle anything left over
var leftoverRecords = people.Skip(queriesNeeded * 250);
BuildAndExecuteQuery(leftoverRecords);

However, while I know how to paramaterize a basic single-line INSERT, I don't know how to go about paramaterizing an INSERT that can have an unknown number of variables in it. Is there a way to do that? How would I go about creating my SqlCommand for this?

Option 2: SqlBulkCopy Class

Or... I could go the SqlBulkCopy route. The only problem I have here is that I can't find anything that indicates how to parameterize this, or if I even need to. Do I need to worry about escaping my data, or handling parameters at all here?

Not much experience with in-memory Bulk Copy here, but I can certainly answer this:

I don't know how to go about paramaterizing an INSERT that can have an unknown number of variables in it.

You do it by adding parameters in the same loop that you use to add them to the query.

To extend your psuedo-code, you would replace this:

   BuildAndExecuteQuery(records);

With something like this:

foreach record in records
{
   Add parameter(s) to the query
   Add the same parameter(s) to the command's Parameters collection
}
ExecuteQuery

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