Sunday, April 20, 2008

How to use SQLBulkCopy in C#

This is code implementation for alternative bcp command prompt of SQL Server for copying the Table records among Local server Databases or Server Databases.

SqlConnection Con = new SqlConnection("Data Source=(Local);Initial Catalog=Pack;user id=sa;pwd=*****");
Con.Open();
SqlCommand Com = new SqlCommand("Select *from TrackDetails", Con);
SqlDataReader Dr = Com.ExecuteReader();


//Destination Database Connection Opening..
SqlConnection DCon = new SqlConnection("Data Source=(Local);Initial Catalog=Muru;user id=sa;pwd=*****");
DCon.Open();

SqlBulkCopy bc = new SqlBulkCopy(DCon);
bc.DestinationTableName = "SQLBulk";
bc.WriteToServer(Dr);
Dr.Close();
Response.Write("Copied successfully");


Just for a demo purpose.you can use the WriteServer method of SQLBulkCopy Class in try,catch and finally to close the stream SQLDataReader and destination connection as well as source connection.