简体   繁体   中英

Insert data from one SQL Server database into a second database for all tables dynamically using C#

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();

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());
        } 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM