CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

How to do Bulk Copy of data from one Database Table to Another Database Table in C# and ASP.Net?
Submitted By Satheesh Babu B
On 3/13/2010 8:02:42 AM
Tags: ADO.Net,ASP.Net,CodeDigest  

How to do Bulk Copy of data rows from one Database Table to Another Database Table in SQL Server Using C# and ASP.Net?

 

SqlBulkCopy class is released in .Netframework 2.0 which can be used for performing bulk copy of data from one table to another table in same database server or different server similar to DTS and bcp utility at high speed. It can also be used to bulk copy from sqlserver 2005 database table to sql server 2000 database table, keeping in mind that destination table will have all the columns matching with the one we are copying from the source.

 

The below code will help us to that,

string connectionString = "Data Source=BABULIVES;Initial Catalog=tempdb;Integrated Security=True";      

        using (SqlConnection sourceConnection =
                   new SqlConnection("Data Source=BABULIVES;Initial Catalog=NorthWind;Integrated Security=True"))
        {

            sourceConnection.Open();
              using (SqlConnection destinationConnection =
                           new SqlConnection(connectionString))
                      {
                     destinationConnection.Open();            

                     using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
                            {
                            bulkCopy.DestinationTableName = "dbo.Employees";

                            try
                            {
                                   bulkCopy.WriteToServer(reader);
                             }
                            catch (Exception ex)
                             {
                                   Response.Write(ex.Message);
                             }
                            finally
                             {                   
      
                          reader.Close();
                             }

                     }

                    }
       }     

 

The above code will copy Employees table rows from database db1 to NothWind database.

 

Happy Coding!!

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..