// Create source connection
SqlConnection source = new SqlConnection(ConfigurationManager.ConnectionStrings["SourceConnectionString"].ConnectionString);
// Create destination connection
SqlConnection destination = new SqlConnection(ConfigurationManager.ConnectionStrings["DestinationConnectionString"].ConnectionString);
// Open source and destination connections.
source.Open();
destination.Open();
// Select data from Products table
SqlCommand cmd = new SqlCommand(@"SELECT customer
,name
,address1
,address2
,address3
,address4
,address6
,address5
,fax
,territory
,region
,class
FROM
[dbo].[slcustm]", source);
// Execute reader
Console.WriteLine("Read data from [dbo].[slcustm] table");
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("Write data to DestinationCustomers table");
// Create SqlBulkCopy
SqlBulkCopy bulkData = new SqlBulkCopy(destination);
//If you are copying larger amount of data don't forget to set the timeout flag. Default value is 30 seconds. 0 = No limit
bulkData.BulkCopyTimeout = 0;
// Set destination table name
bulkData.DestinationTableName = "DestinationCustomers";
// Write data
bulkData.WriteToServer(reader);
// Close objects
bulkData.Close();
destination.Close();
14 May 2015
Copy Data between two different MSSQL Databases on different servers using C#
You can copy data from one SQL table to another using INSERT command with SELECT within same database or databases on same server but things gets little complicated when databases are on two different server. Here is a C# snipplet you can use to copy data between two desperate databases on two different servers. Code is self explanatory with comments. Your source and destination table fields needs to match.
Labels:
.NET,
Bulk Copy Data,
C#,
MSSQL Server,
SQL
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment