We will start by creating a connection to the SQL Server that is acting as a source of data. The following code snippet shows how this is done:
using System.Data.SqlClient; string connectionString = "Data Source=.;Initial Catalog=NTL;User ID=sa;Password=P@ssw0rd"; SqlConnection sourceConnection = new SqlConnection(connectionString); sourceConnection.Open();
Next step is to run commands to get data into a DataReader, following is the code to accomplish the same:
We created a source table 'Table_1' using SQL Server Manager in 'sandeep' database that contains some values to be copied
SqlCommand commandSourceData = new SqlCommand("SELECT * FROM Source;", sourceConnection); SqlDataReader reader = commandSourceData.ExecuteReader(); Connect to a destination table of data using: SqlConnection destinationConnection = new SqlConnection(connectionString); destinationConnection.Open();
Destination table 'Table_2' will be required to fill the data from 'Table_1' using bulk copy
Point to be noted here is that we are using same 'connectionString' as we are copying data to same server. We now have to copy data using bulk copy feature:
SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection); bulkCopy.DestinationTableName = "Destination"; bulkCopy.WriteToServer(reader); reader.Close();
In the end we closed 'reader' and then we can close our connections to the SQL server.In this way data from one table was copied to other in fastest possible way.It is also possible to use single instance of 'SqlBulkCopy' for performing multiple bulk copy operation. This technique is more efficient than using separate 'SqlBulkCopy' instances for each operations.
Get most out of your technology infrastructure investments with Dell
About CIOL | Media Kit | Site Map | Contact Us | Help | Write to us | Jobs@CyberMedia | Privacy Policy
Copyright © CyberMedia India Online Ltd. All rights reserved. Usage of content from web site is subject to Terms and Conditions.