views:

84

answers:

2

I have a DataTable in memory that I need to dump straight into a SQL Server temp table.

After the data has been inserted, I transform it a little bit, and then insert a subset of those records into a permanent table.

The most time consuming part of this operation is getting the data into the temp table.

Now, I have to use temp tables, because more than one copy of this app is running at once, and I need a layer of isolation until the actual insert into the permanent table happens.

What is the fastest way to do a bulk insert from a C# DataTable into a SQL Temp Table?

I can't use any 3rd party tools for this, since I am transforming the data in memory.

My current method is to create a parameterized SqlCommand:

INSERT INTO #table (col1, col2, ... col200) VALUES (@col1, @col2, ... @col200)

and then for each row, clear and set the parameters and execute.

There has to be a more efficient way. I'm able to read and write the records on disk in a matter of seconds...

+6  A: 

You should use the SqlBulkCopy class.

SLaks
Awesome, but do you know if it can be used on temp tables?
John Gietzen
@John Gietzen - the way I usually do it, is to load into a "real" table - then drop it once you're done.
AdaTheDev
Well, that's somewhat doable, but again there are about 10 copies of this app that could be running concurrently. Do you know if a Bulk Copy can be part of a transaction?
John Gietzen
@John Gietzen - if they're all meant to be separate from each other, load into a "temporary" real table - just generate a unique table name at run time to stop them contending. You can do bulk copy as part of a transaction (http://msdn.microsoft.com/en-us/library/wftd1yfz(v=VS.100).aspx) but I've personally never done that
AdaTheDev
Awesome, thanks.
John Gietzen
GOOD NEWS! You can use an external transaction, and you can use temp tables! Down from 20 minutes to 8 seconds!
John Gietzen
+6  A: 

SqlBulkCopy will get the data in very fast.

I blogged not that long ago how to maximise performance. Some stats and examples in there. I compared 2 techniques, 1 using an SqlDataAdapter and 1 using SqlBulkCopy - bottom line was for bulk inserting 100K records, the data adapter approach took ~25 seconds compared to only ~0.8s for SqlBulkCopy.

AdaTheDev
+1, but I'm giving the accept to SLaks because he was a hair quicker. Thanks for the link.
John Gietzen
He's fast and accurate, like a sniper rifle bullet.
James Westgate