Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert 2 million rows into SQL Server quickly

I have to insert about 2 million rows from a text file.

And with inserting I have to create some master tables.

What is the best and fast way to insert such a large set of data into SQL Server?

like image 480
Wadhawan Vishal Avatar asked Dec 05 '12 11:12

Wadhawan Vishal


People also ask

What is the best and fast way to insert 2 million rows of data into SQL Server?

You can try with SqlBulkCopy class. Lets you efficiently bulk load a SQL Server table with data from another source.

How long does it take to insert 1 million rows in SQL?

It takes about 3 mins to insert 1 million rows if I run it in the SQL server and take about 10 mins if I use C# program to connect from my desktop. The tableA has a clustered index with 2 columns. My target is to make the insert as fast as possible (My idea target is within 1 min).

How can I insert 100000 rows in SQL Server?

Create csv file (or some file with defined field delimiter and row delimiter) and use "BULK INSERT" option to load file to database. File can have 100000 rows; there won't be any problem of loading huge file using bulk upload.


2 Answers

  1. I think its better you read data of text file in DataSet

  2. Try out SqlBulkCopy - Bulk Insert into SQL from C# App

    // connect to SQL using (SqlConnection connection = new SqlConnection(connString)) {     // make sure to enable triggers     // more on triggers in next post     SqlBulkCopy bulkCopy = new SqlBulkCopy(         connection,          SqlBulkCopyOptions.TableLock |          SqlBulkCopyOptions.FireTriggers |          SqlBulkCopyOptions.UseInternalTransaction,         null         );      // set the destination table name     bulkCopy.DestinationTableName = this.tableName;     connection.Open();      // write the data in the "dataTable"     bulkCopy.WriteToServer(dataTable);     connection.Close(); } // reset this.dataTable.Clear(); 

or

after doing step 1 at the top

  1. Create XML from DataSet
  2. Pass XML to database and do bulk insert

you can check this article for detail : Bulk Insertion of Data Using C# DataTable and SQL server OpenXML function

But its not tested with 2 million record, it will do but consume memory on machine as you have to load 2 million record and insert it.

like image 195
Pranay Rana Avatar answered Oct 13 '22 05:10

Pranay Rana


You can try with SqlBulkCopy class.

Lets you efficiently bulk load a SQL Server table with data from another source.

There is a cool blog post about how you can use it.

like image 26
Soner Gönül Avatar answered Oct 13 '22 04:10

Soner Gönül