tags:

views:

70

answers:

4

We need to INSERT 2000 records into SQL DB from C# .Net code. For this is there any way to INSERT all 2000 records at a time instead of executing the INSERT query for each record. Also how would be the performance impact of doing this?

Thanks & Regards Padma

+3  A: 

you can do it quickly using SqlBulkCopy:

http://www.dotnetcurry.com/ShowArticle.aspx?ID=323

We use this to import a dataset of about 100,000 records into a SQL table in a few seconds, where 100,000 insert statements took 15 minutes.

rwmnau
That's the way to go, for sure!
marc_s
SqlBulkCopy is seriously one of the must underrated adapters in the SqlClient namespace - it's lightning fast at importing large amounts of data.
rwmnau
A: 

There is no way you can do it in batch from C# code. 2000 rows will be quick to insert though.

One option may be available to you if you have the 2000 records in a flat file, you could copy it to the SQL server and create SP to BULK INSERT the file into a table. Then call the SP from your C# code. I would not bother unless you see having more rows than that and if you have huge target table.

IMHO
What about SqlBulkCopy ??
marc_s
This is **not true**. .NET includes the very powerful **SQLBulkCopy** class which is **THE** fastest way of inserting data into a SQL Database.
ntziolis
IMHO
A: 

Well, you could build a query that has multiple inserts in it:

string sql = "INSERT INTO table (col1, col2) values (@val1,@val2);" +
             "INSERT INTO table (col1, col2) values (@val3,@val4);"

But dealing with the parameters for the command would get a bit tricky.

You can also use DataAdapters and DataTables to do batch inserts. That would probably be the best option, although the usage is a bit strange (not nearly as nice as Java's addBatch() / executeBatch() for example).

Performance wise, you'll almost certainly get a nice performance boost by doing this, although you might need to play around with the batch size a bit to figure out what works best

Eric Petroelje
I don't think this will help much, especially when compared to the performance of SqlBulkCopy....
marc_s
@marc_s - I've found the performance to be pretty good, but I've never tried SqlBulkCopy either.
Eric Petroelje