Reputation: 232
I have used this code. Can anyone help me on the code part to move the data one database to another?
SqlConnection SourceServerName = new SqlConnection(@"Data Source = Stack; Initial Catalog = SSIS2;Trusted_Connection=yes;");
SqlConnection DestinationServerName = new SqlConnection(@"Data Source = Stack; Initial Catalog = SSIS1;Trusted_Connection=yes;");
SqlCommand Cmd = new SqlCommand("SELECT NAME FROM sys.TABLES", SourceServerName);
SourceServerName.Open();
System.Data.SqlClient.SqlDataReader reader = Cmd.ExecuteReader();
while(reader.Read())
{
Cmd = new SqlCommand("TRUNCATE TABLE " + reader["name"], DestinationServerName);
DestinationServerName.Open();
Cmd.ExecuteNonQuery();
reader = Cmd.ExecuteReader();
SqlBulkCopy bulkData = new SqlBulkCopy(DestinationServerName);
// String Dest = reader["name"].ToString();
bulkData.DestinationTableName = reader["name"].ToString();
bulkData.WriteToServer(reader);//reader);
bulkData.Close();
DestinationServerName.Close();
}
SourceServerName.Close();
Upvotes: 0
Views: 89
Reputation: 42494
You can't reuse the DataReader and SqlCommand like you do. Also reusing a connection can give headaches but as you didn't share how or where you created those I left that untouched for now.
// consider wrapping in a using as well
SqlCommand Cmd = new SqlCommand("SELECT NAME FROM sys.TABLES", SourceServerName);
SourceServerName.Open();
System.Data.SqlClient.SqlDataReader reader = Cmd.ExecuteReader();
while(reader.Read())
{
// create a new command to truncate the table at the destination
using(var TruncateCmd = new SqlCommand("TRUNCATE TABLE " + reader["name"], DestinationServerName))
{
DestinationServerName.Open();
TruncateCmd.ExecuteNonQuery();
}
// sqlbulkcopy is IDisposable, wrap in a using
using(var SqlBulkCopy bulkData = new SqlBulkCopy(DestinationServerName))
{
// have a new SourceCmd to get a DataReader for the source table
// create a new connection, just to be sure
using(var SourceCon = new SqlConnection(SourceServerName.ConnectionString))
using(var SourceCmd = new SqlCommand("select * FROM " + reader["name"], SourceCon))
{
SourceCon.Open(); // this is definitely needed
DestinationServerName.Open(); // not 100% sure if this is needed
bulkData.DestinationTableName = reader["name"].ToString();
// WriterToServer knows how to deal with a DataReader
bulkData.WriteToServer(SourceCmd.ExecuteReader());
}
}
}
Upvotes: 2