Last active
July 18, 2017 04:14
-
-
Save ed0507/edbb5a5e7d97ebf6c2d6e791049548e7 to your computer and use it in GitHub Desktop.
SqlBulkCopy Sample - How to copy a table from db to another db using SqlBulkCopy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void Main(string[] args) | |
{ | |
DateTime CopyStartTime; | |
//Connect to source database | |
using (SqlConnection cnSource = new SqlConnection("Data Source=SourceDB;Initial Catalog=SourceDBName;Persist Security Info=True;User ID=uid;Password=pwd")) | |
{ | |
cnSource.Open(); | |
using (SqlCommand cmdSource = new SqlCommand("", cnSource)) | |
{ | |
//Connect to destination database | |
using (SqlConnection cnDestination = new SqlConnection("Data Source=DestinationDB;Initial Catalog=DestinationDBName;Persist Security Info=True;User ID=uid;Password=pwd")) | |
{ | |
cnDestination.Open(); | |
//how many rows in the source table | |
cmdSource.CommandText = "SELECT COUNT(*) FROM SampleData"; | |
Console.WriteLine("Total Rows:{0}", cmdSource.ExecuteScalar().ToString()); | |
//create a SqlBulkCopy Object | |
SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(cnDestination); | |
//How many rows will be copy in a batch | |
sqlBulkCopy.BatchSize = 3000; | |
//time out | |
sqlBulkCopy.BulkCopyTimeout = 100; | |
//which table you want to write in detination database | |
sqlBulkCopy.DestinationTableName = "dbo.SampleData"; | |
//NotifyAfter, it will call the Sbc_SqlRowsCopied when the sqlbulkcopy copied 300000 rows. | |
sqlBulkCopy.NotifyAfter = 300000; | |
sqlBulkCopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(sqlBulkCopy_SqlRowsCopied); | |
//mapping the column | |
//sqlBulkCopy.ColumnMappings.Add("ID", "ID"); | |
//sqlBulkCopy.ColumnMappings.Add("Name", "Name"); | |
//sqlBulkCopy.ColumnMappings.Add("PurchaseDate", "PurchaseDate"); | |
CopyStartTime = DateTime.Now; | |
cmdSource.CommandText = "SELECT * FROM SampleData"; | |
using (SqlDataReader drd = cmdSource.ExecuteReader()) | |
{ | |
sqlBulkCopy.WriteToServer(drd); | |
} | |
Console.WriteLine("All Rows Copied. It spend {0} seconds.", new TimeSpan(DateTime.Now.Ticks - CopyStartTime.Ticks).TotalSeconds); | |
Console.ReadLine(); | |
} | |
} | |
} | |
} | |
private static void sqlBulkCopy_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) | |
{ | |
Console.WriteLine("{0} Rows Copied", e.RowsCopied); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment