Introduction

This article explains how to copy data of one table to another table using bulk copy. In this example I am explaining a scenario when both tables are in two different databases in same server.

First of all design a table by using following scripts in one database and insert some data in it.

  1. Create Table Products  
  2. (  
  3. [Id] int primary key,  
  4. [Name] nvarchar(50),  
  5. [Desc] nvarchar(250)  
  6. )  
  7. GO  
  8.   
  9. Declare @Id int  
  10. Set @Id = 1  
  11.   
  12. While(@Id <= 100000)  
  13. Begin  
  14. Insert into Products values  
  15. (@Id, 'This Is Product No - ' + CAST(@Id as nvarchar(20)),  
  16. 'It Contains Total Product - ' + CAST((@Id+10) as nvarchar(20)))  
  17.   
  18. Print @Id  
  19. Set @Id = @Id + 1  
  20. End  
In above table total 100000 rows are avalibe now create another database and create same table structure of table in that databse. If you want you can create different structure and collumns name also.
  1. Create Table Products  
  2. (  
  3. [Id] int primary key,  
  4. [Name] nvarchar(50),  
  5. [Desc] nvarchar(250)  
  6. )  
Now open visual studio and create an empty web project. In web.config file create two connection string like
  1. <connectionStrings>  
  2. <add name="Source" connectionString="Data Source=*****; Initial Catalog=manish_db; 
  3. User Id=sa; password=*****" providerName="System.Data.SqlClient"/>  
  4.   
  5. <add name="Destination" connectionString="Data Source=*****; Initial Catalog=TestDB;
  6.  User Id=sa; password=*****" providerName="System.Data.SqlClient"/>  
  7. </connectionStrings>  
Here Source connection for reading data from first database product table and Destination connection string for access another database table and paste the data.

Now design a web page by using following code:
  1. <div style ="font-family :'Times New Roman' ">  
  2.   
  3. <asp:Button ID="btnCopy" runat="server" OnClick="btnCopy_Click" 
  4. Text="Copy Product Table Data To Test DB Product Table" Width="398px" />  
  5. <br />  
  6. <asp:Label ID="lblProgRpt" runat="server" ForeColor="Red"></asp:Label>  
  7. <br />  
  8. <asp:Label ID="lblMsg" runat="server" ForeColor="Green"></asp:Label>  
  9.   
  10. </div>  
Now in code behind page of this webpage create following function:
  1. private void BulkCopy()  
  2. {  
  3.    string Source = ConfigurationManager.ConnectionStrings["Source"].ConnectionString;  
  4.    string Destination = ConfigurationManager.ConnectionStrings["Destination"]
  5.                         .ConnectionString;  
  6.    using (SqlConnection sourceCon = new SqlConnection(Source))  
  7.       {  
  8.             SqlCommand cmd = new SqlCommand("SELECT [Id],[Name],[Desc] FROM [manish_db].[dbo].                                             Products]", sourceCon);  
  9.             sourceCon.Open();  
  10.             using (SqlDataReader rdr = cmd.ExecuteReader())  
  11.             {  
  12.                   using (SqlConnection destinationCon = new SqlConnection(Destination))  
  13.                   {  
  14.                         using (SqlBulkCopy bc = new SqlBulkCopy(destinationCon))  
  15.                         {  
  16.                               bc.BatchSize = 10000;  
  17.                               bc.NotifyAfter = 5000;  
  18.                               bc.SqlRowsCopied +=(sender, eventArgs) =>  
  19.                               {  
  20.                                     lblProgRpt.Text += eventArgs.RowsCopied + " loaded...." 
  21.                                     + "<br/>";  
  22.                                     lblMsg.Text = "In " + bc.BulkCopyTimeout +
  23.                                      " Sec " + eventArgs.RowsCopied + "
  24.                                     Copied.";  
  25.                               };  
  26.   
  27.                               bc.DestinationTableName = "Products";  
  28.                               bc.ColumnMappings.Add("Id""Id");  
  29.                               bc.ColumnMappings.Add("Name""Name");  
  30.                               bc.ColumnMappings.Add("Desc""Desc");  
  31.                               destinationCon.Open();  
  32.                               bc.WriteToServer(rdr);   
  33.                         }  
  34.                   }  
  35.             }  
  36.       }  
  37.   
  38. }   
In above code

bc.BatchSize = 10000;
bc.NotifyAfter = 5000;


BatchSize will create a batch of group of data of 10000 and write them into destination table. When 5000 data has been written into destination table NotifyAfter will rage bc.SqlRowsCopied events and show above message .

Here following code:
  1. bc.DestinationTableName = "Products"// Destination table Name  
  2. bc.ColumnMappings.Add("Id""Id"); // source table columns and destination table 
  3.                                     //columns mapping  
  4. bc.ColumnMappings.Add("Name""Name");  
  5. bc.ColumnMappings.Add("Desc""Desc");  
If both the source and destination table structure are same then no need of mapping the table columns.

When we run this webpage and click on button it will show output like.
copy product table data
Summary

This article showed how copy the data of one table to another table of another database using bulk copy.Thanks.I would like to get feedback from my readers. Please post your feedback, question, or comments about this article.